#archived-code-advanced

1 messages · Page 108 of 1

turbid tinsel
#

if that fits your needs

#

a relatively generous free tier of a million monthly events

wind kayak
#

Do you have anything in mind for the middleman web service?

sly grove
#

could be literally anything you're comfortable with

#

even an AWS lambda or something

wind kayak
wind kayak
#

I plan to write json data to a file in unity and then have it read from the producer which will send it to a kafka topic

bold venture
#

i'm looking to hack into https://github.com/Unity-Technologies/Graphics/blob/master/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs#L1400
I want to update that cameraData.renderScale to be always based on lets say "640x320". Current that value is being calculated as a percentage of the players screen resolution. Is it possible to override this cameraData from a custom render pass/feature? I can see you can at least read it from

public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) {
    UniversalCameraData cameraData = frameData.Get<UniversalCameraData>();
    cameraData.renderScale = (.. calculated scale based on monitor resolution and hardcoded resolution);
    // There is no way to "set" this data I think.
}

I'd rather not fully override UniversalRenderPipeline.cs ( is that even possible?).

Alternatively I can see in the "Render Graph Viewer" that there is a texture called _CameraTargetAttachmentA created, if i can resize that before the first blit it would also work I guess?

I'm trying to get a pixelation effect by rendering at very low resolution and then doing a point upscale. For various reasons I don't want to have a full screen render texture on a quad.

frozen ravine
#

Any clue why my camera isn't taking pictures correctly? I made an extension method for the RenderTexture to Screenshot thing and the first image is how it looks in-game and the second image is the result. Any clues why this is happening?

#

I'm first of all confused about what's happening with the colors, but I'm moreso confused by the fact that it doesn't seem to be at the same position that the render texture is at? I made sure the transform is exactly where it should be so I'm just confused

#

I fixed the position thing but I can't figure out the lighting one

#

here is the render texture it generates

#

and here is the PNG

#

is it the color format?

tall kraken
#

Anyone has any idea what “Assertion failed on expression: 'SUCCEEDED(hr)'” error could mean? I’ve been scratching my head for the past 2 days… my drivers are all updated and I tried reinstalling unity/using different versions

#

It happens whenever I open older projects or create new ones

#

I have directx 12

turbid tinsel
tall kraken
#

I tried

#

Even unity 6 preview

#

2022.3
2021.3

untold moth
tall kraken
#

But it doesn’t affect the game at all

untold moth
#

Maybe the log file hase some more unfo

tall kraken
#

As I saw online it has to do with GPU or smt

#

No idea tbh

untold moth
#

Graphics API most likely, but not necessarily. Calls to system API(,or rather the result evaluation) would often look like that

tall kraken
#

I tried changing api in editor but nothing

untold moth
#

The fact that unity doesn't provide any more info on that failure is a bit weird though.

tall kraken
#

No idea

untold moth
tall kraken
#

My pc is off rn it’s almost 2AM here

#

I’ll provide tomorrow

#

Unless I find solution

#

Anyways ty

timid spoke
#

does anyone here know how to handle tilemap transformation matricies? i'm attempting to import a tilemap from a godot game and i'm having trouble migrating the transformation properties that godot provides (allowing flip h/v and transpose)

#

this is where i'm at with my code so far. transposing works but none of the tiles are flipped horizontally or vertically

var transformMatrix = Matrix4x4.identity;
var scale = new Vector3(1f, 1f, 1f);
if (tile.flipH != null && (bool)tile.flipH)
{
    scale.x *= -1f;
}
if (tile.flipV != null && (bool)tile.flipV)
{
    scale.y *= -1f;
}

if (scale != Vector3.one)
{
    Debug.Log($"{scale} (h: {tile.flipH != null && (bool)tile.flipH}, v: {tile.flipV != null && (bool)tile.flipV})");
}
                
transformMatrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale);
if (tile.transpose != null && (bool)tile.transpose)
{
    transformMatrix *= Matrix4x4.Transpose(transformMatrix);
}
timid spoke
full ledge
#

Hello. I'm making a 2d spider that uses its legs to walk. It uses 2d hinge joints. I know you shouldn't use transform.rotate with joints and rigid bodies, but it gives more precision than the chaos of using motor speeds with precise alignments. The weird thing is, it works well with the right side legs, but the left side legs, not so much. they seem to only rotate one way(not consistently). but I'm assuming its going out of the joint limits, hence the full rotation. I only manually rotate the transform of the "thigh" to align it to lock on to its next step target. The left legs freak out sometimes.

        Vector2 footPosition = GetFootPosition();
        Vector2 directionToTarget = (currentTarget - footPosition).normalized;
        float aimRotation = 0f;
        float targetAngle =
            Mathf.Atan2(directionToTarget.y, directionToTarget.x) * Mathf.Rad2Deg;
        float currentAngle = legSegment2.transform.eulerAngles.z;
        float rotationSpeed = spiderController.rotationSpeed * Time.deltaTime; // Adjust the rotation speed as needed
        float newAngle = Mathf.MoveTowardsAngle(currentAngle, targetAngle, rotationSpeed);
        legSegment2.transform.rotation = Quaternion.Euler(0, 0, newAngle);
sacred star
#

Hey, im back, i tryed to uninstall all the packages, and the error is still there, except for the 4 with installed as dependencies, i can't remove them to try ( i think )

untold moth
sacred star
untold moth
sacred star
sacred star
sacred star
earnest heron
#

Hey all,
Anyone knows how should I start implementing fishing line physics like what it is in Red Dead Redemption 2 ?

gleaming onyx
#

Does anyone know what persistent malloc is? accumulates a lot of memory in the memory profiler

upbeat path
gleaming onyx
#

Thé alloc stacks

#

How exactly works malloc in Unity?

crisp temple
upbeat path
#

malloc allocations are not garbage collected, they are C/C++ memory allocations not C#

untold moth
untold moth
gleaming onyx
#

Memory profiler

untold moth
gleaming onyx
#

Yeah, look

#

i dont know how to fix it, i never use malloc

sly grove
#

Things like physics, navmesh stuff, etc

olive cipher
#

Doesnt deep profiling also show you what part of your process is allocating?

gleaming onyx
#

i'm too dumb, i dont understand xd

half swan
# gleaming onyx

Use the hierarchy view instead of the timeline view you have now

#

Click "timeline" on the bottom left

gleaming onyx
untold moth
# gleaming onyx

As it says, it's part of the unity subsystems, so there's not much you can do about it. Though unity could've provided a better job at describing what it's used for.

Only one thing though: are you profiling a build?

#

Also, what are you actually looking for? Optimizing the memory consumption or performance?

gleaming onyx
untold moth
gleaming onyx
untold moth
#

And I'm not talking about regular arrays, but native arrays. There's a difference

gleaming onyx
#

gameobject list and two-dimensional arrays to store block data

untold moth
gleaming onyx
untold moth
#

It's really hard to say what's going on, without having a grasp of your project.

untold moth
gleaming onyx
#

In my code I do not use malloc, in fact and implemented the IDisposable interface

#

to dispose block class, chunk class,

untold moth
#

Are you using any third party assets or plugins that could be allocating memory?

violet valve
#

So regarding what I eventually did - it was enough to just replace my UnitGroup script with a ConcurrentUnitGroup which uses the ConcurrentDictionary internally. What's nice about this is that I can do all the fancy management that I want on worker threads while the main use of the class continues to operate on the main thread. It ended up being super simple. Here is a working skeleton of the class: ```cs
using Sirenix.Utilities;
using System.Collections.Concurrent;
using System.Linq;

public class ConcurrentUnitGroup
{
ConcurrentDictionary<int, Unit> dict;

public ConcurrentUnitGroup()
{
    dict = new ConcurrentDictionary<int, Unit>();
}

public int Count { get { return dict.Count; } }

public delegate void UnitTransactionAction(int unitId, Unit unit, ConcurrentUnitGroup group);
public event UnitTransactionAction onUnitAdded;
public event UnitTransactionAction onUnitRemoved;

public void SetSingle(Unit unit)
{
    if (dict.ContainsKey(unit.id))
    {
        var keysToRemove = dict.Keys.Where(key => key == unit.id).ToList();
        keysToRemove.ForEach(id => TryRemove(id));
    } else
    {
        Clear();
        TryAdd(unit);
    }
}

bool TryAdd(Unit unit)
{
    bool result = dict.TryAdd(unit.id, unit);

    if (result)
        onUnitAdded?.Invoke(unit.id, unit, this);

    return result;
}

bool TryRemove(int id)
{
    bool result = dict.TryRemove(id, out Unit unit);

    if (result)
        onUnitRemoved?.Invoke(unit.id, unit, this);

    return result;
}

public bool AddSingle(Unit unit)
{
    return TryAdd(unit);
}

public void Clear()
{
    dict.ForEach(entry => TryRemove(entry.Key));
}

public void IssueCommand(int id, SelectionTarget target)
{
    dict.ForEach(entry => entry.Value.IssueCommand(id, target));
}

}```

untold moth
#

Or use jobs/compute shaders or something else that is close to low level.

gleaming onyx
untold moth
#

Well, then there's nothing explaining the growing native memory consumption

gleaming onyx
#

courutines?

#

ienumerator can consume memory?

untold moth
#

No, none of that would be making native allocations.

#

As I said before, native arrays(or other collections) and potentially compute/graphics buffers. So anything that might be using these is the culprit.

untold moth
#

Or what are you basing your assumptions on?

gleaming onyx
#

The more you explore the world, the more memory they consume.

untold moth
gleaming onyx
#

By only going about 200 blocks to the left, it barely takes up any memory.

untold moth
gleaming onyx
#

no

untold moth
orchid marsh
#

Or create test scenes with limited functionality/features to see which objects/features are the underlying problem.

gleaming onyx
orchid marsh
# gleaming onyx

Just to be clear, if width is 10 you'll be destroying blocks -10 to 9. Is this your expectation?

#

Same with height

gleaming onyx
orchid marsh
#

What's the purpose of normalizing the coordinate?
When x is -width, the normalized coordinate would be 0.
When x is 0, the coordinate is 0. 🤔

gleaming onyx
#

when i walk 300 blocks this happens XD

gleaming onyx
#

and sometimes i wanna find my object in the array

#

using his global x coordinate

orchid marsh
#

I understand what your intentions are but I'm not sure if you understand that when x is -width it'll produce the same outcome as when x is 0.

gleaming onyx
#

if you use -16 + 16 = 0

#

it works fine

#

i know what you mean

orchid marsh
#

Looks like a waste of processing power as your calling destroy twice on the block

gleaming onyx
#

but if i use 0, the chunk is builded from the 0 to the top

#

from bottom left to top right

#

i wanna build all chunk to left to the right

gleaming onyx
#

i destroy twice

#

that why i destroy my block class storage

#

and my block class MonoBehaviour

#

and the gameobject

#

active blocks

orchid marsh
# gleaming onyx if you use -16 + 16 = 0

So just for simplicity purposes let's assume you've got a 6 chunk world (linear) that ranges x: [-3, 3). Evaluating a single axis only (x, width)... Destroying the (-3, 3) would yield the normalized (0, 3). Since you iterate this and also destroy element (0, 3) as well, there's some redundancy and you may even be possibly skipping or missing half of the elements - very highly possible that you're getting unintentional memory leak (relative to blocks not being freed/destroyed)

gleaming onyx
orchid marsh
#

And likely you're referencing null but have not freed/destroyed the actual elements

orchid marsh
#

where the first three numbers were derived from the negative values

#

relative to (int x = - width; x < width; ++x)... x => normalized where x = -width and width = 3 using the formula coordinate < 0 ? width + coordinate : coordinate -3 => 0 -2 => 1 -1 => 2 0 => 0 1 => 1 2 => 2

gleaming onyx
#

im gonna take a snapshot to compare

worldly pecan
#

How are you handling updating the chunks/deciding when they're going to be released? It could be that you have some hanging chunks that you forgot to release and/or can't reference anymore

worldly pecan
frozen ravine
#

Why doesn't this work? I'm trying to sample the player's pose based on an animation right before rendering the camera and it seems like part of it is working because it's rotating (since for some reason the animation is offset by 90 degrees) but the position is inconsistent like it's sampling different parts of the animation

#

I'm using it to pose the character for these icons, and as you can see, the player isn't in the exact same pose in every icon

#

I'm trying to sample this frame

#

you can see I have the animation plugged in and it's not throwing any errors so I'm not sure why this isn't working

#

(also you can see that the hair isn't affected by the animation sampling for some reason. I assume it's because it's a child to the object butagain, it's rotating properly, just not doing the right position in the pose)

charred drum
#
ProjectWindowUtil.CreateAsset(_newMap, "Map_" + temp_mapName + ".asset");
string path = AssetDatabase.GetAssetPath(_newMap);```
Why isn't this working? I'm trying to get the path of the newly created asset, it's probably trying to get the ``ScriptableObject`` I created...
Is there a way to look for an asset via the name?
worldly pecan
charred drum
#

That would look in the folders? Also, I'm looking for a very specific name (ie, the one I just created. I have a string (temp_mapName)

worldly pecan
#

Wait... I'm a bit confused--what's wrong with using AssetDatabase.CreateAsset? Idk what ProjectWindowUtil is or its advantages

steel snow
#

is there much different between using a List / Array vs unity's Native Array but use persistant allocation ?

Because every time i need to run a job im moving the same managed data to a native array (which is the most performance heavy part), so im thinking why not just put the managed data to a native array once and use that native array all the time and mark the allocator as Persistant ?

#

there must be a downside but docs dont really say much

worldly pecan
#

No, but don't forget to free it

steel snow
#

of course. 🙂

worldly pecan
#

There is downtime in the editor for saftey checks but these aren't applied in build. Also those checks are very minimal, and managed arrays already do their own checks as well

steel snow
#

just wanting to check if any one knows any gotchas with it before i go for it

charred drum
worldly pecan
#

But... aren't you saving it at a path you defined? Why do you need to query the path?

steel snow
#

you have to save first

#

it might help to show the code CreateAsset function

charred drum
charred drum
worldly pecan
#

Don't you want the folder path? What path do you want here?

steel snow
#

ProjectWindowUtil what is this ? i dont see it in the docs

#

is it your own thing

#

confused why you dont just use AssetDatabase.CreateAsset

untold moth
#

Path to eternal life I guess...
@charred drum you'll need to explain a bit better what you're trying to achieve and what the current issue is.

charred drum
#

I'm trying to create a Editor Window, that creates a Scene and a custom ScriptableObject, which names both files to the name (Plus a prefix). I would also want it to add it to the Scenes in Build thing, but I'll sort that out later (If it's even possible)

charred drum
steel snow
#

youre on version 4.6.2?

#

surely not

charred drum
#

No, I'm on version 2022

steel snow
#

i dunno why i can't seem to see any docs on it

charred drum
#

I'm confused too

untold moth
#

This looks like an extremely outdated API

steel snow
#

does VStudio say its deprecated

#

when you over over it

charred drum
#

No, it doesn't...

#

I got this from a forum post quite a bit ago

steel snow
#

that might be from a namespace not related to unity? maybe an asset or some api you imported perhaps

#

either way you should just use AssetDatabase.CreateAsset

untold moth
#

I'd avoid using anything that's not documented at all in the modern docs.

#

You can create assets with the assetdatabase. I don't see why you'd need anything else

charred drum
steel snow
#

you right it does exist but i dunno what that function is doing when i looked at the code:

    [RequiredByNativeCode]
    public static void CreateAsset(UnityEngine.Object asset, string pathName)
    {
        StartNameEditingIfProjectWindowExists(asset.GetInstanceID(), ScriptableObject.CreateInstance<DoCreateNewAsset>(), pathName, AssetPreview.GetMiniThumbnail(asset), null);
    }
#

safe to say thats not what you want anyway based on that code

#

its undocumented so w.e it is they dont want us using it

charred drum
#

I've already used CreateAsset for the ScriptableObject, but I'm not sure how you can create a completely blank scene with it

steel snow
#

like this:

        Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);

        string path = "Assets/NewScene.unity";
        EditorSceneManager.SaveScene(newScene, path);

        AssetDatabase.Refresh();
#

think its only possible from editor folder

charred drum
#

Alr, let me try that

#

Ok, so what it does is it opens a scene with that name

#

But doesn't save it

steel snow
#

you have to tell the asset database to save

#

once you save it, it should be in your asset folder

charred drum
#

Oh wait no, made a typo

#

It works, thanks 🙂

#
string path = AssetDatabase.GetAssetPath(Selection.activeObject) + "/";
ScriptObject_Map _newMap = new ScriptObject_Map();
_newMap.Map_Scene = sceneName;
AssetDatabase.CreateAsset(_newMap, path + "Map_" + temp_mapName + ".asset");
Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive);
EditorSceneManager.SaveScene(newScene, path + "Scene_" + temp_mapName + ".unity");
EditorSceneManager.UnloadSceneAsync(newScene);
AssetDatabase.SaveAssets();
Debug.Log(path);```
Here is my end code
#

But yeah, I have no idea what was going on with that ProjectWindowUtil. I was having a similar issue a while back, and that's the code people suggested I use

untold moth
#

Either these people are time travelers from 10 years ago or don't really know what they're talking about and can't use documentation properly

charred drum
#

I mean, it does work, I just can't rename the files or otherwise get the path

untold moth
#

It does, but that doesn't mean that it's the correct way to do it.

charred drum
#

Yeah

#

Thank you for your help dlich and Sir, I really appreciate it

charred drum
untold moth
north dock
#

Does anyone know if it's possible to render a ScreenSpaceOverlay Canvas to a RenderTexture?

short junco
compact ingot
north dock
umbral parrot
#

I'm working on a system that heavily relies on generics, and I'm having some trouble integrating it with Unity specific stuff. Ideally, I'd have a generic MonoBehaviour and be done with it, but Unity doesn't allow it. So I have to create an empty derived class for every type I want to use with the generic MB. It's not too bad, but I thought it'd be nice if I could auto-generate those scripts. Specifically, I'd want to go through the sources, find every instance of class SomeClass : Generic<SomeType> and create a file SomeTypeMonoBehaviour.g.cs with contents class SomeTypeMonoBehaviour : GenericMonoBehaviour<SomeType> {}. Roslyn's source generators seem like the perfect tool for the job... except that they inject source at compile time, while Unity needs actual physical files so it will let me add the MBs to objects. So, my question is: how can I tell a source generator to save its files somewhere in the Unity project? Any help is greatly appreciated. (Note: I have done some research. I am aware of <EmitCompilerGeneratedFiles>, but I don't know if that's the way to go, nor how to inject that into Unity's auto-generated .csproj files, nor if Unity will care about it in the slightest.)

compact ingot
#

depending on your IDE, it can run the T4 for you

umbral parrot
#

But then wouldn't I loose the benefits of using the Roslyn API? Finding which types need to be generated just from the source files seems like it'd be a pain

compact ingot
umbral parrot
#

I don't really understand what you mean with that. As I'd said, I need to find some classes that derive from a generic class and create new classes that derive from a generic MB based on that

compact ingot
#

in the example signature above the problem is that when creating a new type one has to make ~15 of these empty wrappers you talk about, and making those by hand is annoying. So that particular library has a code generator tool in the editor that just generates them as a starting point when you implement a new type.

scenic forge
umbral parrot
scenic forge
#

I think someone asked a similar question awhile ago though, apparently ECS does something where it can magically generate a class that can be used in editor like regular components. You can search #1062393052863414313 forum to try and find that thread, not sure if it got answered.

#

The other alternative would be doing the reverse, so instead of "write class Internal and ask SG to generate class MB based on it" you would do "write class MB and ask SG to generate class Internal based on it."

#

And of course editor script would be the last resort (since it sucks that you have to alt tab from your IDE to Unity editor whenever you want to trigger editor script, have to wait for recompile, and pollutes version control with a bunch of generated artifacts)

compact ingot
scenic forge
#

Sure, the other two points still stand though.

compact ingot
#

i think its somewhat weird to have a compiler produce artefacts that are inputs on its next compiler run...

scenic forge
#

They are not.

#

Source generated by SG does not participate in the next compilation, nor can they recursively generate from themselves. It's basically an added step to the compilation.

compact ingot
#

thats what im saying, its weird to work around that constraint and do it anyway

#

the SG emitter is for debug/validation/tracking/evidence

scenic forge
#

Oh I don't suggest to emit the files generated by SG.

#

That was talking about Unity editor scripts.

compact ingot
#

i've found it easiest to do that kind of thing (generating monobehaviours etc.) by running a T4 based generator in the IDE, off some reflection/static config. But thats probably not what the OP needs.

#

there is a GameObject based ECS from years back that requires such a generator step, that always felt quite heavy handed and broke all the time.

scenic forge
#

It's a trade off yeah, SG is notoriously difficult to develop and debug, but once you get it working it's really nice that you get immediate update within your IDE.

fathom locust
#

Is there a good way to detect whether a navmesh path is going to make use of a navmesh link, without relying on the NavMeshAgent class?

sly grove
fathom locust
#

No, I've had to avoid using agents because I'm making a vehicle-based game.

half swan
fathom locust
#

If I remember correctly, agents affect the movement of an object, don't they? It's been a while but I vaguely remember this being the reason I avoided them.

misty glade
#

https://www.reddit.com/r/gamedev/comments/bq6c5d/deterministic_physics_dice_rolls_in_a_non/

This looks cool. I've got a question, though - in case anyone's done any sort of 3d physics based dice rolling. How do you prevent "infinite" situations? IE - dice tipped up against other objects, dice on top of each other, etc. Should I just put a cap on the time I sim, and if it goes over that cap, try a different starting set of "bump" velocities and directions?

charred drum
#

This is a pathfinding script I was working on, and I'm trying to make it detect floors and move around, thing is- this worked last night but for some reason always returns true, even if the box shouldn't be triggered

#

Detection code:

Debug.Log(name + " - " + _frontFloor + " (@ " + Time.frameCount + ")");```
Debug cube:
```Gizmos.color = Color.green;
Gizmos.DrawWireCube(transform.position + (NPC_PathfindDir * (charcontroller.radius * 2)) + (Vector3.down * 2.5f), new Vector3(0.2f, 2.5f, 0.2f));```
``NPC_PathfindDir`` is basically ``transform.forward`` in this case
misty glade
#

Oof - use string extrapolation, all that string concatention is hard to read

#
Debug.Log($"{name}:{_frontFloor} (@{Time.frameCount")");
#

checking the code tho, sec

tall ferry
charred drum
#

Also, I'm using CheckBox instead of just raycasting so that way small gaps like, for example in a bridge, won't affect pathfinding

misty glade
#

maybe not, i dunno

charred drum
#

Here's somre more shots of the detection cube, shouldn't be true

misty glade
#

ie, what's charcontroller.radius*2, what's Vector3.down * 2.5f, what's new Vector3(0.2f, 2.5f, 0.2f) * 2, etc

#

I can .. assume? what those mean but if you had some intermediate variables (and you logged them) it might be more obvious to you/us what you're intending and what the problem is

charred drum
#

charcontroller.radius*2 is the radius of the character controller (In this case it's default at 2)
Vector3.down * 2.5f is an offset
new Vector3(0.2f, 2.5f, 0.2f) * 2 is the size of the cube, I put *2 as is half extents but I realize I'm utterly stupid and have removed that

misty glade
#

well you're not utterly stupid 🙂 but I'd make it simpler for yourself by putting a lot more intermediate variables in there so you just really can't goof it up

#
const float characterHeight = 2.5f; // half height? full height?
const float characterWidth = 0.2f; // half width? full width?
float characterControllerRadius = charcontroller.radius * 2;
Vector3 footPosition = Vector3.down * characterHeight;
Vector3 cubeSize = new(characterWidth, characterHeight, characterWidth);
Vector3 collisionCube = transform.position + (NPC_PathfindDir.normalized * characterControllerRadius); // Did you really want to add the down vector to this?

bool isOnFloor = Physics.CheckBox(
  collisionCube, 
  cubeSize, 
  Quaternion.Euler(Vector3.zero), 
  layerMask, 
  QueryTriggerInteraction.Ignore);
#

that might be how i'd debug and write this this

#

(then debug log each of those vars)

#

might seem like I'm trying to de-clever the code but.. imho being clever/cramming stuff into one line = hard to understand/find bugs

charred drum
#

Eh, probably

#

I don't care though

#

Ok, I actually figured out the issue

charred drum
#

Thank you Sharp

tall ferry
misty glade
#

I mean, my reason for doing it would be the networking issues

#

(it's multiplayer/server authoritative)

#

so.. the server would roll randomly, then the client would "see" a physics-dice roll but the rolls are already known

untold pagoda
#

So I added threading to my project and moved the main calculations off to a 2nd thread and it helped alot, but I'm curious if any of this could go on a 2nd thread or if forbidden due to needing monobehavior?

    public void AssignMeshData()
    {
        mesh.Clear();
        mesh.vertices = verticies;
        mesh.uv = uvs;
        mesh.triangles = triangles;
        GetComponent<MeshCollider>().sharedMesh = mesh;
        mesh.RecalculateNormals();
    }

I think the bulk of the time is spent baking physics, as a result of the collider being added.

misty glade
#

I don't see any reason why it couldn't be taken off the main thread, although I dunno if RecalculateNormals() does anything funny - like just flag the mesh for recalculation of normals at a later stage in the tick lifecycle, in which case you'll want that probably to be on the MT

#

or .. you might just want it on the MT anyway in case of any sort of race condition or deadlocking

#

how are you taking items off the MT? with UniTask or something similar?

untold pagoda
#

I sorta figured them last 2 lines were off hte table since it wouldn't even let me use Random.Range in 2nd thread

misty glade
#

it wouldn't let you use Random.Range? lol.. roll your own that's not in Unity.Math 🙂

untold pagoda
#

well for that I just switched to System.Random, that was no big deal

misty glade
#

I wrote a wrapper to random a long time ago using System.Random just because I didn't have a need for seeds/determinism most of the time

#
    public static class NumberUtils
    {
        private static readonly Random _internalRand = new();
        public static int Next(int maxExclusive) => _internalRand.Next(maxExclusive);
        public static int Next(int minInclusive, int maxExclusive) => Next(maxExclusive - minInclusive) + minInclusive;
        public static bool NextBool() => _internalRand.Next(2) == 0;
        public static double NextDouble() => _internalRand.NextDouble();
        public static T Next<T>(List<T> list)
        {
            if (list == null) return default;
            if (list.Count == 0) return default;
            return list[Next(list.Count)];
        }
//... and a zillion more.. colors.. vectors.. positions on a rect border, etc
tall ferry
misty glade
#

Like, if the server says to the client, "ok roll the dice but the results are going to be 1,1,1,1,1" I still need to sim up the physics if I wanna have ... "physical dice"

tall ferry
misty glade
#

it's a board game, so.. server won't even be unity-aware or doing any physics at all

tall ferry
misty glade
#

all good.. just talking it out, thinking of cool solutions

#

my current solution is just to show the dice in UI, but that feels kind of flat

scenic forge
#

Can always have a set of premade fixed animations for each outcome and just randomly pick one that matches.

misty glade
#

might be a bit hard since there'll be ~20 dice rolled per turn

#

I was also thinking that it might be cool if the dice bounced off of the units/environment stuff

long ivy
untold pagoda
#

Also I'm just using System.Threading currently, does Unity off something in Jobs or othre that would be more suitable?

long ivy
#

the job system (+burst) is likely to be a lot more efficient if you can do whatever work you're doing with the mesh inside its restrictions

untold pagoda
#

cool, I'll have to read up on that, haven't touched it yet

worldly pecan
#

You could just do an async call--using the job system may be faster but it has a lot more setup

tall ferry
misty glade
#

Yeah but what do you show on the dice? without simming it ahead of time

#

like if someone rolls the dice and they come up 6, 6,6,6,6,6 and the server is like 1,1,1,1,1 that's gonna feel weird/bad

tall ferry
misty glade
#

Ah, gotcha

tall ferry
#

It doesnt sound like something solvable at least if the server isnt physically rolling it, you would have to have a deterministic system (not unity physics)

#

Solvable meaning everyone sees the exact same movement

misty glade
#

Well, that's sorta what I'm doing. 🙂 Everyone is going to see the same "result" but not the same animations

#

I'm gonna physics sim throwing the 20 dice (from start to finish, all in one frame), keep track of position, rotation, then fudge the initial rotation so it ends up on the number I want, and then "replay" the sim one frame at a time just using RB

#

if I "kick" the dice quickly in the first frame then you shoudn't be able to see the cheat

scenic forge
#

If you don't require having random animation every time, simming a bunch of animations and randomly picking one is fine.

misty glade
#

I can't sim them ahead of time though since they'll bounce off of units in the game

scenic forge
#

Then you just change the dice texture so that the desired numbers end up on top.

misty glade
scenic forge
misty glade
#

sure, can do that too

scenic forge
#

Ah, that's essentially just what the post is describing.

frozen ravine
#

so I have the ability to take photos in my game and I notice that they come out way different. After some research, I found out that this is because my game is in a linear color mode and the pictures are in gamma. How do I fix this?

#

this is my code that makes the texture. I've tried changing linear to true and false and neither worked and I tried changing the TextureFormat and that didn't change anything either

#

here are the settings for the render texture

#

you can see that it looks just fine, it's just the texture that the code is making that's off

hasty coyote
#

RenderPrimitivesIndirect works worse than DrawProceduralIndirect.. why? maybe i do something wrong.
DrawProceduralIndirect is around 300FPS
while
RenderPrimitivesIndirect is around 170FPS
shouldnt be RenderPrimitivesIndirect newer and better method?

https://github.com/AndrzejKebab/UnityVoxelMeshGPU

GitHub

GPU voxel mesh generation and drawing in Unity. Contribute to AndrzejKebab/UnityVoxelMeshGPU development by creating an account on GitHub.

untold moth
hasty coyote
tired fog
#

So porting to unity 6, before I didn't get any errors, now im getthing this

RenderTexture.Create failed: random writes are not supported for depth only textures - format D16 UNorm (90).
#

This is how I'm creating the Render Texture

  RenderTextureDescriptor descriptor = new RenderTextureDescriptor(textureResolution,
      textureResolution, RenderTextureFormat.RHalf, 16, MipLevels)
  {
      useMipMap = true,
      autoGenerateMips = false,
      enableRandomWrite = true,
      #if UNITY_6000_0_OR_NEWER
      graphicsFormat = SystemInfo.GetCompatibleFormat(GraphicsFormat.None, GraphicsFormatUsage.Linear)
      #else
      graphicsFormat = SystemInfo.GetCompatibleFormat(GraphicsFormat.None, FormatUsage.Linear)
      #endif
  };

  DepthTexture = new RenderTexture(descriptor);
  DepthTexture.Create();
#

Any idea how to get the right format to use?

hasty coyote
#

DrawProceduralIndirect

#

RenderPrimitivesIndirect

fast falcon
#

Hello, is there a way to have the title of a script shown in the inspector (red arrow) be changed by a variable in that script? (in this case the Name variable so it would be something like "Music: Phase1") instead of Music Track (Script) )

#

I've looked online but I haven't been able to find anything helpful so far. I just need to know where to look.

upbeat path
fast falcon
upbeat path
fast falcon
fickle mango
fast falcon
untold moth
hasty coyote
untold moth
#

As well just generally see what execution path it takes and what parameters are used. Perhaps it is faster in the first case because it omits some calculations.

untold moth
hasty coyote
#

DrawProceduralIndirect

untold moth
#

Interesting. It doesn't register any actual draw calls. I wonder if it's just a profiler issue or there's something more to it.

hasty coyote
untold moth
# hasty coyote and what should i look here for?

Well, start from comparing 2 captures: one with RenderPrimitivesIndirect and one with DrawProceduralIndirect.
You could also make both calls in the same frame to avoid jumping between the captures.

Compare the used shaders, the command used for the draw call and it's parameters. Then you could also use the debug tab to step through the shader as it executes and compare it in both cases.

tawny steppe
#

Hey ive been running into a problem with the a* pathfinding package where my agents just walk right into the wall

frozen ravine
#

So I'm using a render texture to take pictures in my game and as you can see, it looks a lot darker in the final output than in-game (it looks a lot brighter in game). I'm pretty sure this is because the game is using a linear color space, but I'm unsure how to convert it when I export it. Does anyone have any advice about this?

#

is there some way to just convert a texture's color space?

tired fog
#

What would be the best way to have an asset rename feature sync to an editor window? Currently the title of the editor window comes from a GUI content, and I would like to update it every time the name has changed.

tired fog
tired fog
tired fog
#

About the physics itself, you dont really want to make real forces simulation. Playing with animations that look like its applying forces and having a simpler implemtation will make it waay easier to work with (and I doubt red dead uses physics itself looking at some videos)

earnest heron
tired fog
#

Or at least that's how I would do it

earnest heron
# tired fog Rod line it's a matter of bending it with a shader. Line itself is just a line r...

Hmm, I'm mostly looking for a correct approach to achieve something like RDR2. I think it is not just line renderer and probably mesh generator or something.
Also I think it is not that much physics based, or at least it is not effected by collisions.
I'm asking about performance because I want to omit techniques which are not performance-wise at least. I don't want to waste too much time on an approach which can't optimize it that much. For instance, if I want to use rope physics probably I'll waste too much resource there because of no collision impacts.

tired fog
# earnest heron Hmm, I'm mostly looking for a correct approach to achieve something like RDR2. I...

Yeah, I mentioned physics because you mentioned physics initially, but I agree that i don't think it's physics based either. I don't think there's any mesh generator either because you can see that the line is almost always in tension (at least on the active part of fishing). Plus, in any case, you are probably better using a line renderer with multiple points even if you want some bending when throwing it, and calculate the positions yourself to bend accordingly

#

I think you should start on something and act on the problems as you find them. The line renderer approach should not take you more than max a couple of hours, and im being really generous there

#

What might be more troublesome is the rod bending, but it's just math

#

And once you got the animation and visuals part separte of the point of the fish in the player, its way easier to just move the fish and then everything follows

earnest heron
tired fog
#

That's why I also asked what was your previous experience. Looks like you already got it figured it out!

sweet niche
#

Though it'd be weird for it to still be HDR after all the postpocessing has run 🤔

young kelp
upbeat path
young kelp
#

aight

drowsy cloak
#

this is the code i use to build bundle

public class AssetBundleBuilder : MonoBehaviour
{
    [MenuItem("Assets/Build AssetBundles")]
    static void BuildAllAssetBundles()
    {
        string assetBundleDirectory = "Assets/AssetBundles";
        if (!Directory.Exists(assetBundleDirectory))
        {
            Directory.CreateDirectory(assetBundleDirectory);
        }

        BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.StandaloneWindows);
    }
}
#

i dont think it should be the issue

#

it worked before but it dosnt anymore and i cant pinpoint why

quartz turtle
#

Hey everyone 👋

#

I have tried everything I can, running out of ideas now

quartz turtle
copper kernel
#

Hi, I can ask you a question, how can I change the value of some components in the Input Manager with a script (for example, "Horizontal")
and if this cannot be done, then what is the way to implement it

dapper cave
#

in your experience, which is cheaper: Physics.Raycast or Navmesh.Raycast?

fallen yacht
#

Am currently modding a game that uses harmony though that detail itself isn't toooo important. Am optimizing said game in question since the devs for it aren't willing to do it themselves even with help and one major issue is all the game object and component spawning during even bullets ect. Have attempted an object pool and it kind of works but truth be told the code is just way too convoluted to catch all these edge cases and thus ends up impractical to fix/maintain. So another solution came to mind which I use for my own works. Where one would have a custom allocator of sorts that gives you a block of memory based in input size similar to malloc but when said memory is "returned" it never actually gets cleaned up by system memory. The end result is such that once the game "warms up" it roughly keeps allocated about what it needs and has minimal overhead such heavy polymorphism and nested allocations aren't anywhere near such a big deal. I know GCs are supposed to solve this but reality is when they release memory back to system that defeats the entire point and the data pool required is rather large. So would anyone happen to know if there's a way to either modify the GC or tweak a setting such it never releases memory back to system? It's entirely worth while to reserve anywhere from 4GB to 8GB extra memory.

untold moth
# fallen yacht Am currently modding a game that uses harmony though that detail itself isn't to...

Well, then you'll have a memory leak. Because there's no guarantee that you would be able to reuse the same memory, simply because the allocated blocks might not be of the required size or alignment. Besides, I bet that most of the overhead is not from the allocation/deallocation itself, but from invoking the destructors and cleaning up the objects.

Also, changing the behaviour of the GC would at the very least require you have access to the engine source code.

Finally, are you sure that the issue is the GC? Did you actually profile the project?

fallen yacht
#

Eeeew darn it >.<

autumn bane
#

Discussing modding is against the rules, by the way

fallen yacht
#

We've done extensive testing and the custom object pool at the least did a major impact, when it didn't crash at least.

#

The heck?

#

I guess I should find a community server in that case sorry for not reading.

#

I didn't want to believe the destructor calling would be that expensive but honestly the nesting is sooooooooo deep it very well could be.

#

Righto off I fuck thank you.

#

Also I know I'm a DOD nut but someone please spread the word of at the very bare min object pooling to push the industry in the right direction please and thank you much you all have an awesome day.

livid kraken
#

I would venture to say that the industry is pretty much familiar with object pooling 🤣

azure meadow
#

How can I "listen" to an object destruction?
What I need: I have delegates. Behaviours connect to those delegates. Programmers forget to disconnect from said delegates on object destruction. I get wacky errors when the delegates fire callbacks on destroyed objects.

My attempt to solve: An extension method on Behaviours so you can do something like SafeConnect(delegate, ()=>{}). This function somehow needs to hook into the behaviour destruction to remember to unhook the delegate on object destruction.
(Somehow similar to DoTween's SetLink)

Now... how can I listen to an object destruction? 🥲

#

Oh, I could make a behavour to do the linking and the behaviour itself would take care of himself 🤔
something like GetOrAddComponent<TheDelegateinator>().SafeConnect(delegate, ()=>{})

#

Oh my god... I made a Maid/Janitor pattern for unity 🤦‍♀️

compact ingot
azure meadow
#

oh 👀
I have unitask, lemme check, thanks!

compact ingot
worldly pecan
#

Hey guys, I need to use a mutable static field in Unity's Job system. I'm doing this because I have some settings that I do not know in compiletime, but only need to set once in runtime. Burst provides this utility for mutable statics here https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-shared-static.html

Unfortunately, the documentation is a bit lacking on this. To use the generic I need to initialize it on load using GetOrCreate with a key and a context. Does anyone know what this key and context means? If I make a template of a struct, can I then use the struct type as the key? Can I use a struct as a context? My sharedstatic won't be changed on a job so I don't need to care about synchronization.

autumn bane
# worldly pecan Hey guys, I need to use a mutable static field in Unity's Job system. I'm doing ...

The context is the unique “key” of passed types. You have the option of either passing one type as the context or two types (context and a sub-context). The goal with using types this way is to uniquely identify a given SharedStatic. There’s internal hashing of the type to produce a unique identity for each SharedStatic. You would most simply use the type containing the SharedStatic the key, as long as there is no other SharedStatic that does the same.

You can use generic types for the context/sub-context, which comes in handy for where you want to create data associated to specific types.

worldly pecan
#

Oh so as long as the context+subcontext is a unique type combination it should hash differently then?

#

Thanks!

dreamy basin
#

Pls I need help can some tell me what the problem is i have been try for days just on how to shoot but I keep getting error

thin mesa
dreamy basin
#

Fine .Pls can't someone just help me out

thin mesa
#

not until you post something that someone can actually read

dreamy basin
#

Ohh like what my pic is not clear to you should I resend it

spare sleet
thorn flintBOT
dreamy basin
#

Did you see any errors in my code

thin mesa
spare sleet
#

He's trolling I believe, dont get roughed up by it

#

His name looks familiar anyway

dreamy basin
#

Am sorry I don't understand

#

What else should I do I Post the picture of what I wrote and I still don't get what you mean

spare sleet
thorn flintBOT
dreamy basin
#

Should I write it or what

spare sleet
#

Yes or use one of the paste sites if it is really large

dreamy basin
#

So you mean I should write the code in the link above

spare sleet
#

Write the code in a code block or if it is large then use the link and copy and paste the URL and paste it in #💻┃code-beginner

dreamy basin
#

OK I get

spare sleet
#

Yeah I understand you meant to ping me

dreamy basin
#

using UnityEngine;using System.Collections;using System.Collections.Generic;public class rig : MonoBehaviour { [SerializeField] private GameObject projectilePrefab; [SerializeField] private float shootspeed = 20f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetButtonDown ("fire1")) { shoot (); } } void shoot() { GameObject projectile = Instantiate (projectilePrefab, transform.position, transform.rotation); Rigidbody rb = projectile.GetComponent<Rigidbody> (); rb.velocity = transform.forward * shootspeed; }}

#

Hello

spare sleet
dreamy basin
#

No

spare sleet
#

No?

modern coral
#

Hello

dreamy basin
#

Am new on discord

spare sleet
#

It does need to go in #💻┃code-beginner and you need to follow what the code guidelines say to post code

dreamy basin
#

Okkkkkkkk

#

Meet me there

arctic shell
#

Hello! I am struggling with implementing Item Drops in my Unity game. First I am trying to do a Promo Item drop that happens when the user first starts the game for the first time.
I think I am doing everything correctly but I am just not seeing the items in my steam inventory. The Item definition is created and looks like this: https://pastebin.com/pFg54NVp
Currently my AddFirstItem script looks like this: https://pastebin.com/WSeZHg11 but it just runs in a loop because the item is not found in the inventory.
What am I doing wrong? Inventory service in steam developer is allowed of course. In "Economy" the url is also correct. Why is it not working? 😦

earnest heron
#

Hey all,
I made fishing rod line with Verlet Integration and I want to add throwing part. What is the correct way to do that ? I should modify something on the last point on the line ? I want to implement something like RDR2.

sage radish
#

You can think of the line as purely visual. The part you need to get working is the hook/bait physically simulated for the throw, bobbing on the water and reel. You can make it fully physically simulated as a Rigidbody, and use forces to simulate the throw, buoyancy, and reel. After that's all done, you just connect your verlet rope between the end of the fishing rod and the hook.

#

It's also possible to use the verlet integration to apply forces to the hook, to implement the reeling and drag during the throw, but not necessary.

earnest heron
# sage radish It's also possible to use the verlet integration to apply forces to the hook, to...

Thanks for the reply.

I have the same idea too. As a separate logic for the hook/bait. But still I should connect the last point on the line to the hook/bait, right ? So when it is not in throwing state hook/bait position and rotation are updated based on the line last point because of hanging behavior and when I want to throw it I should update the last point on the line based on the hook/bait when its Rigidbody is activate ?

Also does it make sense to change the connection length between points by lerp when it is during throwing part ?

For implementing throwing based on Rigidbody what is your suggestion ? Do you think AddForce or AddRelativeForce is enough ?

hybrid belfry
#

Hi, is there a way to call a function with more than 1 parameter using UnityEvent?

sage radish
# earnest heron Thanks for the reply. I have the same idea too. As a separate logic for the hoo...

I guess it depends on how realistic you want the simulation to be. You can totally go all the way and simulate it entirely with the verlet integration. You just need to simulate as if the particle/node at the end of the rope is heavier than the rest. That approach makes the most intuitive sense, but might be more difficult to tune.

With forces, you can just apply an upward/forward impulse force for the throw, and then calculate the distance between the hook and the end of the rod. If it's greater than the length of the line, apply a force to pull it towards the rod. This is not too dissimilar to how verlet integration works, except it also applied forces in the opposite direction if the distance is less than it's supposed to be.

earnest heron
misty glade
sage radish
earnest heron
# sage radish You have to tune how stretchy/stiff the line is, how many particles are in it, w...

Hmm, got it. Thanks. actually I've been working on the same thing somehow but I couldn't achieve it. So probably I should continue working on this approach more. At least now, I know I'm on the right track.
btw, by rigidbody approach, I shouldn't adjust the length of the line ?
Also I adjust the length of the line by increasing connection line between each particle/node. Does it make sense ?

sage radish
# earnest heron Hmm, got it. Thanks. actually I've been working on the same thing somehow but I ...

I'm not sure what the best approach would be for lengthening the line. The simplest would be to increase the distance between the particles, but then it also becomes lower resolution, visibly and can affect simulation quality too. Alternatively, you can try adding additional particles at the rod end of the line, as if they are being unwound from the reel, but I'm not sure I've seen that done before.

#

With the rigidbody approach, you will need to have some variable representing the length of the line. If the rigidbody gets pulled further away by something, the length will have to be increased to account for that, up to the max length of the reel. But the length should only be decreased if the player is reeling it in.

earnest heron
#

Awesome, thanks a lot.

torn rose
#

@earnest heron As mentioned, you should probably adjust the length of the line by inserting new particles rather than spacing out the points as this has a significant impact on behaviour, if you want to retain visual plausibility.

Mass in sims is used for constraints resolution within the system.

Since you are familiar with verlet integration, I suggest looking into positions* based dynamics. It's similar to what you're already doing in the sense that the new velocities are driven by the delta in position.

If you go with PBD, which is fairly simple to get a grasp of, you can establish constraints such as distance constraints between 2 particles. Your line could be a series of particles, sequentially connected by distance constraints, with a higher mass at the end. You could simulate it entirely physically while retaining great visual plausibility.

#

Hell you could even throw in buoyancy constraints so that it looks accurate when hitting the water

#

And of course, it makes it trivial to apply external forces like the gravity or your wind system

sage radish
#

The only thing that is more difficult to implement with verlet integration is interactions with colliders and rigidbodies. It's possible, but usually more limited, like a select few primitive colliders. Full interaction with colliders will require a more complex approach to be performant.

#

But other than that, it's a much more interesting and promising approach.

torn rose
#

Ya, can't hook onto unity's space partition, so need your own spatial hash + common interface that wraps around physx components and your own

#

can confirm its a pain

sage radish
#

You could also do both. The hook can be a Rigidbody and you can attach the line to it, computing the forces between them. This is similar to how joints/constraints in PhysX work.

#

The line still won't collide with anything, but at least the hook can be hit by boats and not go through colliders around the water.

earnest heron
# torn rose <@404165687997890584> As mentioned, you should probably adjust the length of the...

Yup, inserting new particles is a great idea. I hope I don't get to any obstacles during implementing 🤞

Hmm, what do you mean about mass ? Could you tell me where should I add that ? I thought I should add that like _particles[i].pos += _particles[i].mass * gravity * deltaTime * deltaTime

Oh, I'll research about that. I don't know much about that, just I've read about 3 ways for implementing Verlet Integration which I think one of them is this one you mentioned.

The distance constraints between 2 particles you just mentioned here is not something common in Verlet Integration ? I mean I already made this constraint between particles in this way:

for (int i = 0; i < _particles.Length - 1; i++)
{
    Vector3 delta = _particles[i + 1].pos - _particles[i].pos;
    float length = delta.magnitude;
    float percent = (_connectionLength - length) / length * 0.5f;
    _particles[i].pos -= delta * percent;
    _particles[i + 1].pos += delta * percent;
}

Which I added iteration on that because of accuracy and stiffness.

torn rose
#

Yeah, so with what you have there. When you compute the error, divide it by the sum of the inverse masses for the particles

#

e.g. particle 1's mass is 1, particle 2's mass is 3.

w (aka inverse mass) = 1/1 + 1/3, and then when you move the particles back towards their respective gradients, multiply the gradient * error * that particle's respective inverse mass

earnest heron
torn rose
#

this way, you'll have whichever particle has the higher mass cover less of the distance

#

I assume connection length is your rest length? Then error = restLength - currentLength
gradients are your normalized delta and its opposite vector.
e.g.

// Where .InverseMass = 1f / mass
var w = a.InverseMass + b.InverseMass;

if (w != 0f)
{
    var delta = b.Position - a.Position;
    var length = math.length(delta);
    var error = restLength - length;

    if (error != 0f)
    {
        var gradient1 = math.normalize(delta);
        var gradient2 = gradient1 * -1f;

        var s = -error / w;

        a.Position += gradient1 * s * a.InverseMass;
        b.Position += gradient2 * s * b.InverseMass;
    }
}
earnest heron
torn rose
#

Fastest implementation? Whatever you're familiar with and yields good enough results I guess?

sage radish
#

It will be difficult to replicate RDR2 with other approaches, I think.

earnest heron
torn rose
#

When you are solving that constraint, you're essentially computing the error based on what their distance apart is, and what it should be.

Now if you wanted to make that constraint happy and give it a big error of 0, youd move the particles in a way that satisfies the condition. Should the particles move an equal distance if their mass is not the same? Most of the time, the answer is no.

earnest heron
earnest heron
torn rose
#

the distance constraint and usage of mass is atypical for verlet integration, seems like a mix of PBD and other sequential solving methods

earnest heron
torn rose
earnest heron
torn rose
earnest heron
torn rose
#

Well that'd depend on the order in which you've initialized/inserted your particles.

I mean the one that's the farthest apart when you're throwing your line

earnest heron
torn rose
#

Sure, because verlet/pbd is sequential solving, when you're solving your distance constraints, you're solving them one by one and the outcome of each individual constraints solved is going to have an impact on the ones remaining, but not on the ones before that. It's a bit abstract, but the general idea is that whatever feels the most important to your simulation should probably be processed first

#

The impact of this is attenuated by the amounts of substeps

glossy lynx
#

Anyone here I need help

#

Dayum it look so empty

#

I want to move a 2d gameobject in a perfect circle, how to do it? Without using parent/child (with script)

#

Tag me please

thin mesa
white pulsar
#

Ok so i've tried to do this on my own and i cant figure it out, so i'm gonna ask here.

Workin on a 2D Top down "Realistic" tank controller. By realistic i mean that all the player controls is either the Left track or the Right track, W & S controls the left track, I & K controls the right track.

What i'm greatly struggling on is making the tank rotate correctly. When only one track is accelerated, the tank is supposed to rotate around the stopped track, either clockwise or counter clockwise (depending wether the moving track is accelerating or reversing.)

I need to simulate this movement using Rigidbody2d, and only modifying the "velocity" and "rotation" properties of the rigidbody. Making the tank move according to its current rotation is EZPZ (since its just rotating the input from the player by the rigidbody's rotation), the main issue again, is figuring out how to make it rotate around a pivot and modify the velocity & rotation accordingly.

Here's the script itself, i'm working on this on an empty project to remove any unecesary baggage.
https://hastebin.com/share/aqodafalew.csharp

wary blaze
#

Does anyone know whether, when calling multiple Async Unity methods (like Resources.LoadAsync, SceneManager.LoadSceneAsync, Adressables.LoadAssetAsync, and Addressables.LoadSceneAsync), the requests are always completed in order?

For example, let's say I execute 50 requests and add the returned async op objects (in whatever form they are), to a list. Now I want to check if any of them are done. My understanding is, if I start at index 0 (the first async op queued), once I find an async op that is not completed, I can stop checking the rest because they cannot complete before any that were queued before them.

Is that assumption correct? Or do I need to actually check all 50 because they can be completed randomly?

scenic forge
#

No. Asynchronous operations are assumed to be independent from each other.

wary blaze
#

Okay, cool. Then I'll check them independently.

#

Thanks!

scenic forge
#

You start cooking an egg and downloading a movie at the same time, there's no reason the computer can magically know to not finish until the egg in your pan is done cooking.

wary blaze
#

haha yes, I was just confused because there is mention of some blocking behaviour when using async ops like these. But it looks like that is unrelated to what I was asking here. Thanks!

#

Actually another question after reading the page I linked above. It says this:

Be aware, if activateOnLoad is set to false, the entire async operation queue is stalled behind the blocked scene load operation. This is not limited to scene load requests. Any asynchronous request is blocked until the scene is allowed to activate. This means yield retruns and callbacks cannot trigger until the queue is unblocked. If multiple scene load operations are started with activateOnLoad=false it can lead to inconsistent behavior. For example,

{
    AsyncOperationHandle<SceneInstance> handle1 = Addressables.LoadSceneAsync("level1", LoadSceneMode.Additive, false);
    AsyncOperationHandle<SceneInstance> handle2 = Addressables.LoadSceneAsync("other", LoadSceneMode.Additive, false);

    yield return handle1;  //will sometimes trigger, sometimes not
    yield return handle2;  //will never trigger
}```

Whichever of the two loads gets to "loaded but not activated" first blocks the queue and fires its completion/yield/task events. In this case, if "level1" loads first, its yield return proceeds, but execution is stuck on handle2 forever. If "other" loads first, then even though handle2 is done, handle1 cannot finish. Which scene loads first has nothing to do with which one is requested first in code.
#

" If "other" loads first, then even though handle2 is done, handle1 cannot finish. Which scene loads first has nothing to do with which one is requested first in code." - This I understand

#

" In this case, if "level1" loads first, its yield return proceeds, but execution is stuck on handle2 forever". This one I do not understand. If level1 loads before level 2, then won't the yield return handle2 be allowed to trigger?

scenic forge
#

That sounds like some implementation details of how they are loaded. yield return handle in a coroutine isn't magic, the handle still needs to give an "okay I'm done now, you can proceed with the rest" signal, and it sounds like the situation above will cause the handles to never fire those signals and thus stalling the coroutine forever.

#

What are you trying to achieve?

wary blaze
# scenic forge That sounds like some implementation details of how they are loaded. `yield retu...

Right, I guess my misunderstanding was due to when the "signal" is fired. No worries, I think I may understand it better now, thanks! As for what I'm trying to do, basically queue up multiple load calls and then manually control when they are "activated" (because the activation phase, which involves main frame integration, is very costly if multiple operations are allowed to complete in the same frame).

#

I think the way I'm doing it will avoid the issues mentioned on that page, but only one way to find out!

white pulsar
#

that sounds... wild if true

#

i really need to find a course online for trigonometry because thats something we've never seen properly in my uni where i just studied videogame design and i decided to specialize in programming

#

nevertheless, if you do figure it out somehow lmk and i can try it out

#

bet it'd feel as iluminating as the time i learnt how to properly use a debugger instead of debug logging everything, lol.

#

i kinda do understand vectors to a certain degree, rotations with quaternions, radians, cosine, etc are the things i struggle with since i've never handled them. all i know is how to rotate a vector by x rotation and thats about it. lol

#

yeah,

dull raft
# white pulsar Ok so i've tried to do this on my own and i cant figure it out, so i'm gonna ask...

You might be able to avoid the math and just use joints and such... I haven't really played with them before, but I got curious. This is with RBs on the body and each track. Each track has a Fixed Joint to the body.

I couldn't get the desired turning behavior by fiddling around with RB values, so I just froze a track's position if it has no input and it's not already moving... I reckon there's a better solution though.

Movement code

white pulsar
#

i definetly plan on doing that if i cant get it to work by directly modifying a single RB's velocity and rotation.

#

but if its possible to make it work by directly modifying the velocity and rotation then that'd be perfect

white pulsar
#

is the fact that its in 2d complicate matters a lot?

#

which would be... kind of ironic? since its one less axis to worry about lol

spare sleet
#

2d is as complicated as 3d, you can even use 3d vectors for 2d if you would want, if you understand one you should be able to apply to another

white pulsar
#

fair enough, can i expect you to like... make something out? if you cant thats allright. not like i can force you

torn rose
#

@white pulsar Since it's operated as one entity, you need to cheat a bit.

One way to do this would be to get the point between center of tank and mid point of either track. Compute the distance between both to get the radius.

Once you have the radius, (moveSpeed * Time.fixedDeltaTime) / radius should give you the delta in radians that you should travel for this given step.

Compute the offset with cos(currentRotation + delta) * radius for the x component, sin(currentRotation + delta) * radius for the y component
Add that offset to your tank's current position. That will give you the position where your tank should be if it had rotated around one track for that frame.

At that point, you can simply compute the delta between that position and your current position, and add that as a force with whatever the forcemode that ignores mass is.

white pulsar
#

i could do that since i dont really want to have more than 1 rigid body per "entity" if that makes sense.

but yeah, ideally the output values would just be the rotation and velocity.

#

its alright

torn rose
#

Tracks are not simulated independently, you're not gonna get a physically based animation here.

white pulsar
#

the animation doesnt matter atm, just the movement of the entity

#

apologies, i should've specified that from the beginning

worldly pecan
#

Ok this definately isn’t a good solution, but off the top of my head.

If you have a vector V1 from the center of the tank to a tread, and another vector in the direction we want to go, V2. The angle we have to rotate is

V3 = V1+V2
angle = arccos(dot(norm(V3), norm(V1))

Then you should apply the rotation and move forward in the new direction you are facing–hope this helps!(I have no confidence that this works just some mental math)

#

if you press A, V1 is the vector to the left tread, if you press D, V1 is the vector to the right tread. V2 is always the vector facing forward

#

Feel free to criticize me 😅

tall ferry
worldly pecan
#

Sorry I wrote this in a rush, norm is normalizing the vector, and I mixed up V1 and V2 later.

worldly pecan
worldly pecan
tall ferry
# worldly pecan Also wdym by vector norm? Like the magnitude? Norm should implicitly mean normal...

dont need to read this link but norm is a thing https://en.wikipedia.org/wiki/Norm_(mathematics) but yea i guess it only makes sense to mean normalized in this server.
you should probably restate the exact problem you're trying to solve because all i see is getting an angle (not sure why its needed even).
https://docs.unity3d.com/ScriptReference/Vector3.Angle.html
There is also a built in function to get the angle

worldly pecan
#

Oh figures there’s a way. Yeah but this is the most barebones physics solution for this task(which is good if you don’t want to overcomplicate it with a lot of extra functionality rigidbody provides).

Also why not just call Norm magnitude? It’s like mathematicians just wanna confuse everyone.

tall ferry
worldly pecan
uneven root
#

Hey all, I've never worked with 3rd party plugin in Unity and I'm having some trouble using this one : https://github.com/xioTechnologies/x-IMU3-Software/tree/main/Examples/CSharp
It's a lib to interface with a IMU.
On the GitHub repo I've been able to download a .dll, .lib and .h file that I included in my unity project, but I can't figure out how to reference the ximu3 class present in the plugin as done in the example. I tried the using directive, the [Dllimport] directive but without success. What am I missing ?

GitHub

Contribute to xioTechnologies/x-IMU3-Software development by creating an account on GitHub.

white pulsar
#

I know my employer won't like it that I'm gonna try these solutions when it's a holiday here where I live but I'll try it anyways

white pulsar
#

Tank related, managed to build this thing which is working quite... well it seems

works only for the left track but should be easy to modify for the right track.

#

All I know is that if the movement speed gets too high the angle change is too high. Which tbh I can't do much about it? Since changing it causes the tank to no longer rotate on its appropriate pivot

misty glade
#

Using var makes it hard to know what speed is. A vector? A float? Also, naming a local the same as a member is gonna give you a bad time. Name the local speed something different.

Not quite sure what the problem is, though? Why do you normalize v1 before getting the angle? What is the return tuple? What's "movement" - speed? location? acceleration? Why is "angle" (in the return tuple) not actually the angle, but the angle times the delta time and speed?

The intent is ... confusing from this snippet...

earnest heron
#

@torn rose @sage radish Hey, sorry for pinging. You are absolutely free to ignore my message here. Just pinged you because we already had a conversation about my problem and you are expert on that.

So in the morning, I added Rigidbody and force to the hook/bait for throwing that and Verlet Integration on the line. Also for unwinding the line, I made 200 particles which for instance from 0 to 180 are in the start position (tip of the rod) and their positions are always same as tip of the rod with no Verlet Integration impact and from 181 to 199 are affected by Verlet Integration.
When I need to unwind the line on the reel, I add to the total number of particles which are affected by Verlet Integration based on the deltaTime and it kinda looks okay.
The problem I have right now is, the curve on the line is converse of RDR2 and I don't understand why that happens. Probably because of stiffness ? Do you have any idea what is the issue ?

Bait and line codes:

public class FishingBaitHandler : MonoBehaviour
{
    [SerializeField] private float _force = 10f;

    public bool IsHanged { get; private set; } = true;

    private Rigidbody _rigidbody;

    void Awake()
    {
        _rigidbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter(Collider other)
    {
        _rigidbody.isKinematic = true;
    }

    public void Throw(Vector3 direction)
    {
        IsHanged = false;
        _rigidbody.isKinematic = false;
        Vector3 axis = Vector3.Cross(direction, Vector3.up);
        Vector3 modifiedDirection = (Quaternion.AngleAxis(30, axis) * direction);
        _direction = direction;
        _modifiedDirection = modifiedDirection;
        _rigidbody.AddForce(modifiedDirection * _force, ForceMode.Impulse);
    }
}
soft dune
#

Do I have to write my own HttpValidationProblemDetails and ProblemDetails models in Unity in order to deserialize 401 responses or is there a way to use JsonUtility to do that?

torn rose
#

More specifically, this line
"The problem I have right now is, the curve on the line is converse of RDR2 and I don't understand why that happens. "

earnest heron
torn rose
#

Environment looks nice by the way

sage radish
#

I'm trying to find actual reference footage, but it's difficult to find one where the line is in shot or visible at all.

torn rose
#

Yeah, honestly I also thought it looked great.

That being said, if you want to tweak the behaviour, I still don't understand what you mean. The curve as in the position of the bobble over time while it's been cast?

sage radish
#

Oh hmm, maybe not. This looks more like in RDR2.
https://youtu.be/mvenRLJvEaM?si=hTcV63eVHGKn2YQU&t=177

Film excerpt from the movie Casting & Strategy. Links below in the description. This is for both the beginner and the advanced fly caster. Casting instructor Ronny Lagoni Thomsen takes you on a trip to many different fishing locations to demonstrate fishing strategy and double hand fly casting in real fishing conditions.

© Wide Open Outdoor Fil...

▶ Play video
earnest heron
sage radish
torn rose
#

Ah I see

sage radish
#

Maybe there's not enough gravity acting on the line. It almost seems like it's being affected by air drag, which I don't think is intentional.

earnest heron
#

Yup, what @sage radish said, sorry about that.

sage radish
#

Or some energy is being lost somehow

torn rose
#

One thing is for sure, it's not tight enough. The line feels very loose once it's being cast. I think I would address this first.

Maybe try this. Instead of releasing particles based on the frame delta and crossing fingers the rate matches the motion, perhaps you could simply not constrain the particle closest to the fishing* line. Sample its distance to the tip of the fishing line. If the distance is greater than it should be in function of the resolution of the line, then you generate a new distance constraint and you attach it to the next particle, and you release the next particle.

This way you'd insert particles based on the actual requirements

earnest heron
earnest heron
#

btw, did you check those 2 scripts too ? @torn rose @sage radish

#

Okay, got what you mean @torn rose. I'll try to add that and test how does it look. It makes sense I guess.

torn rose
#

You are treating all distance constraints the same

#

From glancing over the code

earnest heron
#

I changed my code to use mass like this but not sure about that and I don't know how I can take advantage of that.

private void UpdateParticles(float deltaTime)
{
    for (var i = _totalNumOfParticles - (int)_currentNumOfParticles + 1; i < _totalNumOfParticles; i++)
    {
        Vector3 velocity = (_particles[i].pos - _particles[i].oldPos) * _friction;
        _particles[i].oldPos = _particles[i].pos;
        _particles[i].pos += velocity;
        _particles[i].pos += (_gravity / _particles[i].inverseMass) * deltaTime * deltaTime;
    }

    for (int i = 0; i < _totalNumOfParticles - _currentNumOfParticles; i++)
    {
        _particles[i].pos = _pin.position;
    }

    if (!_baitHandler.IsHanged)
    {
        _particles[_totalNumOfParticles - 1].pos = _particles[_totalNumOfParticles - 1].oldPos = _baitHandler.transform.position;
    }
}

private void ConstraintParticles()
{
    for (int i = _totalNumOfParticles - (int)_currentNumOfParticles; i < _totalNumOfParticles - 1; i++)
    {
        Vector3 delta = _particles[i + 1].pos - _particles[i].pos;
        float length = delta.magnitude;
        float error = _restLength - length;
        float sumOfMass = _particles[i].inverseMass + _particles[i + 1].inverseMass;
        float percent = error / length / sumOfMass;
        _particles[i].pos -= delta * percent * _particles[i].inverseMass;
        _particles[i + 1].pos += delta * percent * _particles[i + 1].inverseMass;
    }

    _particles[_totalNumOfParticles - (int)_currentNumOfParticles].pos = _pin.position;

    if (!_baitHandler.IsHanged)
    {
        _particles[_totalNumOfParticles - 1].pos = _baitHandler.transform.position;
    }
}
torn rose
# earnest heron I changed my code to use mass like this but not sure about that and I don't know...

Here

var a = _particles[i]
var b = _particles[i + 1];
var w = a.InverseMass + b.InverseMass;

if (w != 0f)
{
    Vector3 delta = b.pos - a.pos;
    float length = delta.magnitude;
    // The magic number to satisfy the constraint
    float error = _restLength - length;
    if (error != 0f)
    {
        // What to scale the vectors with
        var s = -error / w;
        // The directions
        var gradient1 = delta.normalized;
        var gradient2 = delta * -1f;
       
        a.pos += graident1 * s * a.InverseMass;
        b.pos += gradient2 * s * partifles[i + 1].InverseMass
  }
}
#

Untested but it should work, let me know if you run into issues

earnest heron
torn rose
#

No, you are applying the correction based on the current* magnitude

#

float percent = error / length / sumOfMass;
_particles[i].pos -= delta * percent * _particles[i].inverseMass;

The current length should only be factored in to determine the error

#

Why the masses matter here is because your bubble should feel heavier. If all particles are treated the same within the simulation, you will not be able to properly illustrate that.

You are cheating this a bit by reassigning the last particle to the bauble's position after solving the constraints. This kind of works in the sense that'll force all the particles down the line to bridge a larger gap during the next step to satisfy the constraint.

What should be done is the particle with the bauble should have a higher mass. When resolving the distance constraint, the particle attached to the one with the bauble will move more than the one with the bauble, when attempting to make the constraint happy. Consequently, all the particles down the chain will end up being affected by that.

e.g. if the error between bauble particle and the next particle is 1 for a given step, if the mass of the bauble is significantly higher, the other particle will be responsible for closing most of that gap, forcing the rest of the particles closer, thus giving more influence to the higher mass one

#

provided youre solving from last

fleet sapphire
#

hello

earnest heron
earnest heron
torn rose
earnest heron
#

What should I should do about the stiffness ? I want to make it heavier so it looks less stretchy when it is hanging.

torn rose
#

Well accounting for masses for one

earnest heron
#

btw, does it make sense I put mass here too ?
_particles[i].pos += (_gravity / _particles[i].inverseMass) * deltaTime * deltaTime; ?

torn rose
earnest heron
torn rose
#

good luck

floral marten
#

does anyone have a guide on how to use graphics fences with compute dispatch and AsyncGPUReadback?

#

I'm feeling kinda lost and the docs are devoid of examples in this realm from what I can tell

snow stirrup
#

I apologize if this is the wrong channel, but the ad button is clickable in testing, but not the game.

frozen imp
sage radish
# floral marten does anyone have a guide on how to use graphics fences with compute dispatch and...

Are you dispatching the compute shader as async, with Graphics.ExecuteCommandBufferAsync? If not, you don't need a fence to use AsyncGPUReadback. I haven't used fences before. They seem simple to use, but maybe deceptively so. I would assume it's just calling CommandBuffer.CreateGraphicsFence(GraphicsFenceType.AsyncQueueSynchronisation, SynchronisationStageFlags.ComputeProcessing) after dispatching the compute shader, using that return value to wait for it in either another non-async command buffer or Graphics and then creating the async gpu readback request in the command buffer or Graphics

floral marten
sage radish
misty glade
#

I want to use a library that has a DLL for .net standard 2.0, but it's missing the Microsoft.Bcl.HashCode dependency. Fine, np, I grabbed that DLL from nuget, but now I'm getting conflicts between unity stuff that's using Microsoft.Bcl.HashCode from netstandard 2.1.

Is there a way to .. get the library I want to use to use the 2.0 version and the unity stuff to not use that DLL?

sage radish
floral marten
#

yeah I'm specifically doing that to make it synchronous to rule out issues

#

and because there's no built-in synchronous GPU download into nativearrays from what I can tell

sage radish
floral marten
#

yeah idk why

#

is GraphicsBuffer.SetData() synchronous as well? as in, waits for the GPU queue

#

or would I have to fence this manually

sage radish
#

I don't think you ever need to use fences unless you're using Graphics.ExecuteCommandBufferAsync, which is the only way to queue commands into the async compute pipeline, if one even exists on the GPU.

floral marten
#

alright

sage radish
floral marten
#

I'm guessing the issue has to be somewhere else then, unrelated to synchronization

#

do compute shaders have issues with reading and writing to the same RWStructuredBuffer, even if the different groups read/write their own dedicated section?

sage radish
#

If each thread has its own index/section, it's no problem. If it's all within the same thread group, I think you need to use memory barriers in the shader to ensure there are no race conditions.

#

But I've not used the thread group stuff for anything more than examples, so I'm not the best person to ask.

floral marten
#

yeah each thread is accessing a unique part of the buffer

#

and it does work,, for the most part

#

I'm starting to wonder if maybe there's some kind of silent behavior with uninitialized or out of bounds memory in the compute shader, so that it cancels or something

sage radish
#

Are you using Mathf.CeilToInt when computing the number of dispatch threads? That always gets me.

floral marten
#

yep, using (x+iv-1)/iv

floral marten
#

for context, this is for a selection system in my 3D modeling tool, and this is what happens

#

green = box selection hover
blue = selected

#

so sometimes, the blue applied selection just, doesn't happen, and the green stays, which it shouldn't (the apply step should clear the hover state)

#

but! the thing that's curious is that, the more I do this, and the more I select, the more rare the bug becomes

#

and if I select the whole thing, sometimes the issues goes away entirely, so, maybe it's got something to do with dynamic buffer resizing, or, the compute shader making assumptions about elements being in range, when the buffer is too small, or something

#

the selection buffer is a packed uint structured buffer, with two bits per selection state (hovered and selected), and one uint worked on per thread

sage radish
#

Do you have any bounds checks in the shader, to early exit if the thread id is out of bounds? I don't think you need to on DX11, but you do on other graphics APIs, so you should always do that.

floral marten
#

yeah

sage radish
#

And you're not touching the contents of the buffer at all after starting the async gpu readback?

floral marten
#

not as far as I know, if .WaitForCompletion() makes it synchronous

#

I've also tried the managed array one, the same issue still happens

sage radish
#

Hmm. Do you have any explanation for why it seems the hovered selection becomes flipped in Y screen space after you release?

#

Could be a clue 🤔

floral marten
#

kinda, I think the flip the lesser of the issues

#

the flip is likely because I'm reading from unity's global shader variables, which mneans that if other parts of the unity editor sets things like the _ProjectionParams.x it would flip

#

and I'm guessing it's maybe not fully synchronous when running it in GUI.repaint?

sage radish
floral marten
#

maybe I can shove it into a command buffer to see if it's more consistent

misty glade
#

@floral marten love your content btw - you're a superhero

floral marten
#

o, thank you SCWblushy

misty glade
#

I'm having a weird issue with my A* pathfinding that's utterly killing Unity, and I'm not quite sure where the issue is.. or how to debug this.

My pathfinding loop is essentially something like bool TryGetPath(HexPoint from, HexPoint to, List<HexPoint> map, out List<HexPoint> path) and it works brilliantly on a single click to get the path and highlight the squares.

When I changed it to calculate the path in update() while mouse is down, it works for about 20 frames and then just dies. The weird part is that .. as best I can see, Unity isn't crashing in the GetPath method, but instead in between frames...

I am taking the returned List<HexPoint> path and emitting an event that individual hexes subscribe to and turn their own highlight on/off if they're "in" the path, so maybe something's going on there..

Anyone got any ideas/strategies on how to debug this? Code available upon request obv

#

path highlights on click

#
        private HexPoint _lastMousePosition = HexPoint.None;
        private void Update()
        {
            if (Input.GetMouseButton(0))
            {
                v("Getting mouse position...");
                HexPoint target = GetMousePosition();
                v($"Got {target}.");
                if (target != _lastMousePosition)
                {
                    _lastMousePosition = target;
                    v($"Checking path for {target}");
                    List<HexPoint> path;
                    HexPoint.TryGetPath(HexPoint.Origin, target, _map, out path);
                    ShowPathChanged?.Invoke(path);
                    v($"Done with {target}");
                }
            }
        }

Unity hangs after some number of passes through this chunk - but it always makes it to "Done with".. it never dies in the middle of the TryGetPath method that I assumed with be the issue.

#

(unity is hung completely here - those are the last lines in the console)

#

can't stop playmode, exit unity, etc.. have to kill the process with a knife

sly grove
#

See where your main thread is hanging

misty glade
#

good idea

#

standby

floral marten
#

hmm well for one you're allocating a new list every time instead of reusing the same one, so if it contains a lot of data you'll pressure the GC a lot

misty glade
#

Yeah - definitely there's some bad optimization stuff going on here, was gonna tackle that in a second pass

#

You'd have more than a comment if you saw my A* implemention innards 😛

#

(But that shouldn't kill unity so thoroughly.. at a minimum life would return after GC burped, I would imagine)

#

hm.. I don't know what to do with this..

#

maybe an issue with a race condition on some of my internal lists?

#

hard to tell but looks like something related to something in System.Collections

sly grove
misty glade
#

🤷‍♂️

#

I'm certainly not doing anything async in here

#

Should be all sync on MT as far as I'm aware

thin mesa
#

looks like not the main thread but a burst thread

misty glade
#

the objects (unity MBs) that are subscribed to the C# events.. unity doesn't do any magic to thread those, right?

thin mesa
#

no, but you do need to change to the main thread to see what it is doing

misty glade
#

oh, ok.. lemme try again (restarting unity)

thin mesa
#

just use the dropdown menu i screenshot to change the thread you are viewing

misty glade
#

Like, is the following problematic in any non-obvious way?

#
public class MechMiceMap : BetterMonoBehaviour
{
        public Action<List<HexPoint>> ShowPathChanged; // emits the event with a list to the path
}

public class TerrainHex : BetterMonoBehaviour // 200+ of these
{
        public void Initialize(HexPoint p, MechMiceMap map)
        {
            _map.ShowPathChanged += OnShowPathChanged;
        }
        private void OnShowPathChanged(List<HexPoint> path)
        {
            Cursor.ShowMoveCursor(path.Contains(_location));
        }
}
#

(there's ondestroy unsubscribes, I just omitted it from the above)

#

but shouldn't matter, terrainhexes live "forever" here

#

Got this one this time

#

what is the main thread? there's many here that VS attached to

sly grove
#

Probably that 114 one

#

That is running your code

#

RuleOfCoolStudios?

misty glade
#

yeah

#

hm... what would.. that mean? it's stuck on a readonly getter

thin mesa
#

start stepping through it to see what it's doing, it isn't likely stuck on that specific line

sly grove
#

So maybe just a really huge IndexOf call?

#

How big is that list?

misty glade
#

Oh, ok, I'm able to step through it now.. I'll mash through a bit and see if that helps

sly grove
#

Or an infinite loop inside Update

misty glade
#

it's definitely in the TryGetPath though

sly grove
#

Hmm there's no loop in Update so nevermind there

misty glade
#

I mean, the maps' pretty big so pathfinding worst case could be bad.. 331 hexes it looks like

#

it's entirely possible I have a bug in my A* implementation, this is .. like.. first pass debugging

sly grove
#

You could easily have a factorial algorithm or something

misty glade
#

I can paste the code for it but... asking anyone to load this into their brain is a big ask 😛

sly grove
#

TryGetPath code would be good to see

misty glade
#

it should be lean but.. hard to know for sure

#

I'll pastebin it, gimme a few minutes, gonna step through a bit and see if anything pops out

#

but honestly.. it's a lot to load into your brain 😛

sly grove
#

I'd jump to the TtyGetPath stack frame and step through from there

misty glade
#

AHHHHHHHHHHHHHHHHH

sly grove
#

Everything else in the trace looks straightforward

misty glade
#

I think I found the problem already.

sly grove
#

Yay debugging!

#

Ah yep

misty glade
#

looks like I didn't catch the HexPoint.None from the path finding algorithm lol

#

and since i hardcoded my HexPoint.None to that "real" value of absurd size... having the mouse click "in between" the hexes (there's like a one pixel gap) is leading my A* pathfinding to .. you know.. try to find a path to a hex several million units away

#

In retrospect, pasting the code might have been helpful because.. it was in the first couple of lines

#

Check if the map contains from but not if the map contains to

#

Thanks again PB, add it to the tab 🍻

#

(you too @thin mesa)

#

(honestly if PB ever were able to actually collect the beer tab he's earned from me in the past few years it'd break me)

#

honestly it's pretty fast even for how badly optimized it is

#

i'll dig into optimizing it more later.. maybe it's using gigs of ram and I just don't know yet 🙂

bright carbon
#

Question: Is there anyway of telling which gameObject fired and event?

I have a multiple cursors for different players in a game. When a key is pushed, it fires the event that it has been pushed. I just want to know which instance of object(s) pushed the button.

tired fog
misty glade
#

Nope, fixing that now

#

Just had an error in the "backtracking" part of the code where it backtracked from the end to the start without keeping them adjacent

#

So each tile highlighted is, in fact, one step closer, just not necessarily adjacent to where you are 🙂

#

A* is hard.

#

Now time to optimize.. maybe.. or maybe leave it for another day since my brain already hurts

#

(now witness the power of this fully armed and operational A* star)

tall ferry
bright carbon
#

I see

tall ferry
#

Stuff like that doesnt look like it should be an event in the first place, but not really sure what you're doing with it.

floral marten
#

wait so,, if I have a compute shader, can I expect this to behave?

cs.SetInt("_Blah",0);
cs.Dispatch(...);
cs.SetInt("_Blah",1);
cs.Dispatch(...);```
#

because I'm getting behavior suspiciously similar to what I would expect if setting properties wasn't synchronous

floral marten
#

..if I instantiate the compute shader, and use the clone for the blah=1 case, everything works fine

#

what in the world

sage radish
floral marten
#

I'll try

#

yeah, same issue ;-;

floral marten
#

Thread.Sleep(20) before each Dispatch makes it work

#

GL.Flush() does nothing, Graphics.WaitOnAsyncGraphicsFence also does nothing

#

only sleeping the thread, or, using two separate compute shaders, makes it work

#

the heck

sage radish
# floral marten the heck

Very weird. It must be something to do with the editor rendering loop being weird. I've never observed anything like this or seen anyone talk about it.

floral marten
short junco
#

https://docs.unity3d.com/ScriptReference/ScreenCapture.CaptureScreenshot.html

How can I apply the superSize logic in the screen capture method here? I want to extract the content of my editor window, but the image quality changes depending on the zoom ratio, so it is blurry.

private static void CaptureWindowScreenshot()
{
    EditorWindow inspectorWindow = EditorWindow.GetWindow( typeof( Editor ).Assembly.GetType( "UnityEditor.InspectorWindow" ) );
    inspectorWindow.Focus();

    EditorApplication.delayCall += () =>
    {
        int inspectorWidth = (int)inspectorWindow.position.width;
        int inspectorHeight = (int)inspectorWindow.position.height;

        Color[] pixels = UnityEditorInternal.InternalEditorUtility.ReadScreenPixel( inspectorWindow.position.position, inspectorWidth, inspectorHeight );

        Texture2D inspectorTexture = new Texture2D( inspectorWidth, inspectorHeight, TextureFormat.RGB24, false );
        inspectorTexture.SetPixels( pixels );

        byte[] bytes = inspectorTexture.EncodeToPNG();
        System.IO.File.WriteAllBytes( Application.dataPath + "/InspectorScreenshot.png", bytes );
    };
}
bright carbon
misty glade
#

GL on game jam! (first year in 4 that I'm unable to play 😭)

grizzled valve
short junco
#

I have a SO with these field but when i press plus on inspector i can't add a new value because of reference type i guess how can i fix that ?

Also i have to use reference due to GPNodeData base class , if i dont use reference the derived classes of GPNodeData dont serialize their derived fields

Also should i use nested SO files and if i use that how can i register callbacks to sub so files changes like rename-callback , delete etc,

There is a OnOpenAsset callback but i cant find other things should i use asset preprocessor for that ?

       [SerializeReference] public List<GPNodeData> NodeDatas = new List<GPNodeData>();
    [Serializable]
    public class GPNodeData
    {
        public GPElementType NodeType;
        public string GUID;
        public string NodeTitle;
        public bool Expanded;
        public GPSerializableVector2 Position;
    }
using System;

namespace GP.Serialization.DataTypes.GPType
{
    [Serializable]
    public class GPSelectorNodeData : GPNodeData
    {
        public GPSelectionData SelectionData;
        public GPSelectorNodeData()
        {
            SelectionData = new GPSelectionData();
        }
    }
}
glossy lynx
#

Sorry idk where to ask for help

#

Can I ask here

fresh salmon
#

The three code-* channels are reserved for code issues only. If you can't find a channel, ask in the default general talk one: #💻┃unity-talk

tawny sand
#

What is the best way to detect when the individual sides of a box collider trigger move in and out of collisions?

dusty wigeon
floral marten
# sage radish Very weird. It must be something to do with the editor rendering loop being weir...

this is about as minimal of a repro we could come up with for the compute shader shenanigans

using UnityEditor;
using UnityEngine;
[ExecuteAlways]
public class Ashl : MonoBehaviour { // add this to a game object
    public ComputeShader cs; // assign the compute shader in the inspector
    private static GraphicsBuffer gpuBuffer;
    static uint frameid;
    void OnEnable() => SceneView.duringSceneGui += SceneViewOnduringSceneGui;
    void OnDisable() {
        SceneView.duringSceneGui -= SceneViewOnduringSceneGui;
        gpuBuffer?.Dispose();
        gpuBuffer = null;
    }
    void SceneViewOnduringSceneGui( SceneView obj ) {
        if( Event.current.type == EventType.Repaint )
            Dispatch( frameid++ % 20 == 0 ? BoxAction.Apply : BoxAction.Preview );
        SceneView.RepaintAll(); // <-- just to make it re-trigger repaint like an update loop
    }
    void Dispatch( BoxAction action ) {
        gpuBuffer ??= new GraphicsBuffer( GraphicsBuffer.Target.Structured, 1024, 4 ) { name = "googhg" };
        cs.SetBuffer( 0, "_gBufSelection", gpuBuffer );
        cs.SetInt( "_BoxAction", (int)action );
        cs.Dispatch( 0, 1024 / 64, 1, 1 );
        if( action == BoxAction.Apply ) {
            uint[] dataAll = new uint[gpuBuffer.count];
            gpuBuffer.GetData( dataAll ); // downloads the data from the GPU
            uint data = dataAll[0];
            bool works = data == 0xFFFFFFFF;
            string color = works ? "ffffffaa" : "ff2222ff";
            string msg = works ? "works fine so far" : "BUG HAPPENED";
            Debug.Log( $"<color=#{color}>{msg}: {data:X}</color>" );
        }
    }
    enum BoxAction { Preview = 1, Apply = 2 }
}```
echo crown
#

how do i fix this? (im making a gtag fan game)

half swan
sage radish
# floral marten this is about as minimal of a repro we could come up with for the compute shader...

Trying to recreate this. Haven't been able to, but I believe it. My first thought is that the Repaint GUI event is the issue. Have you tried using something else, like EditorApplication.update and EditorApplication.QueuePlayerLoopUpdate();? The script you provided forces the scene view to constantly refresh even if no updates or mouse movements have happened which, for a box select like you're making, shouldn't be necessary, right?

floral marten
#

using 2022.3, built in RP, not in play mode

#

it happens regardless of whether the force update is there or not, it just makes debugging a little faster

floral marten
#

..and it only seems to happen in D3D11

#

I can't repro this when using any other render platform

sage radish
#

I've tried both with URP and built-in in 2022.3 and get the same thing.

floral marten
sage radish
floral marten
#

very similar in the actual case yeah

#

in the actual use case it comes across as selection being broken for the first 30 selections or so

#

but after that it works consistently

floral marten
#

I just identified a,, hecking big clue

#

so the bug is that _BoxAction has the wrong value in some dispatches

#

I tried writing an reading frame index as well, and somehow the frame id was always correct

#

and so I wondered what the difference was between the frame int and the box action int

#

and the one difference is that frame ID changes every dispatch, while the box action doesn't

#

so,, I decided to try - what if make the box action different every frame, in the unused bits of its uint?

#

and now it works

#

what the absolute heck

sage radish
#

I... don't know... I mean, Unity's managing the default cbuffer for global uniforms. Maybe whatever check is in place for detecting and uploading changes is bugged.

#

You can create and write your own constant buffer, but that's a bit of a hassle.

#

Alternatively, _BoxAction could also be a shader keyword to avoid the property altogether, but it doesn't feel good to just bypass this issue when it could be happening with other properties...

floral marten
#

yeah, I have found a bunch of workarounds, but they're a little clunky and I'm kinda scared I'll run into this again unless I understand exactly how it goes wrong

sage radish
#

Well, I tried it with a custom cbuffer, but it's the same

floral marten
#

I think the best workaround for me would be to use another structured buffer for params, instead of using properties

#

that way I can still clearly define types in the data, and I don't have to add like a custom layer on top of everything to special case every property setter

short junco
#
            PropertyField serializedSelectionField = new PropertyField(serializedSelectionProperty);
            serializedSelectionField.RegisterValueChangeCallback(OnValueChange);
        private void OnValueChange(SerializedPropertyChangeEvent evt)
        {
            SerializedProperty serializedProperty = evt.changedProperty;
            string deserializedValue = serializedProperty.stringValue;
            if (string.IsNullOrEmpty(deserializedValue)) return;

            bool isInteger = int.TryParse(deserializedValue, out int value);
            serializedProperty.stringValue = GPSelectionData.SerializeValue(isInteger ? value : deserializedValue);
            bool needToUpdate = serializedProperty.serializedObject.ApplyModifiedProperties();
            if (needToUpdate)
            {
                serializedProperty.serializedObject.Update();
            }
        }

How can i update serializedSelection field without triggering on value change , if its trigger endless loop corrupts data due to my (ISerializationCallbackReceiver - Serialize , Deserialize methods)

rare canyon
#

Hey, I posted a question into #🔊┃audio that I could use some help with if anyone here has some experience with FMOD

orchid cedar
#

I'm trying to render a few thousand grass blades, with a parameter determining if they have been cut or not. I'm using a graphics buffer and (currently), Graphics.RenderMeshInstanced. Supposedly, this method has a limitation of 511 instances.

When I look at it in the rendering debugger, it appears to render all instances, in chunks of 584. The positions spawn correctly even for the new grass blades, but the problem is, it will only draw them "correctly" for the first batch.

Additional batches seem to have random positions or are randomly cut or not. Any insight into this behaviour, and how I might be able to hack around the limit?
I'm still confused as to why it breaks for the first batch, then seems to work in some capacity for the next, still modifying the instances, just incorrectly

orchid cedar
#

I've tried converting it to use Graphics.RenderMeshIndrect instead but am having difficulty converting the script (nothing will draw currently)

Before I call Graphics.RenderMeshIndirect() in my update loop, I initialize it with the code below

public struct GrassBladeInstanceData
{
    public Matrix4x4 objectToWorld;
    public float isCut;
    public float SpriteIndex; // Randomly pick a grass sprite
    public static int Size()
    {
        return sizeof(float) * 4 * 4
            + sizeof(float)
            + sizeof(float);
    }
}

private RenderParams CreateRenderParams(Material mat){
        RenderParams rp = new RenderParams(mat);
        rp.matProps = new MaterialPropertyBlock();
        return rp;
    }

public void GenerateGrass()
{
    commandBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments, 1, GraphicsBuffer.IndirectDrawIndexedArgs.size);
    commandData = new GraphicsBuffer.IndirectDrawIndexedArgs();
    // If no random positions are set, generate them
    grassMatInst = new Material(grassMatMain);
    rp = CreateRenderParams(grassMatInst);
    grassInstance = new GrassInstance();
    grassInstance.mesh = mesh;
    grassInstance.gbInstData = new GrassBladeInstanceData[numGrassBlades];

    for(int i = 0; i < numGrassBlades; i++)
    {
        ... (Get all positions, create grass matrix, set it below)
        rp.matProps.SetMatrixArray("_ObjectToWorld", grassMatrix);
    }
    commandData.baseVertexIndex = mesh.GetIndexCount(0);
    commandData.instanceCount = (uint)numGrassBlades;
    instancesBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, numGrassBlades, GrassBladeInstanceData.Size());
    instancesBuffer.SetData(grassInstance.gbInstData);
    rp.matProps.SetBuffer("_PerInstanceData", instancesBuffer);
}
#

which I access in my shader from

struct InstanceData{
    float4x4 worldMatrix;
    float isCut;
    float SpriteIndex;
};
StructuredBuffer<InstanceData> _PerInstanceData;

void GetIsCut_float(out float Out){
    Out = 1;
    #ifndef SHADERGRAPH_PREVIEW
    #if UNITY_ANY_INSTANCING_ENABLED
        Out = _PerInstanceData[unity_InstanceID].isCut;
    #endif
    #endif
}

which is accessed in shadergraph. It worked fine with Graphics.RenderMeshInstanced when it was in shadergraph (and others have gotten Graphics.RenderMeshIndirect working with it) so I don't think it is the problem

Any help would be greatly appreciated, I've trowled the discord archives for similar issues and am at a loss

frozen ravine
#

so I'm trying to "flip" my model for my game, what's the best way to do this?

#

I have a character in a fighting game who can face left or right, but I can't rotate them 180 degrees because then they don't face the camera properly

#

my first instinct was to just make the X scale -1 but that messes up the rig in weird ways

#

you can see the character facing the right looks normal, but the character facing the left has less-bent knees and is sinking into the ground a bit

#

is there a good way to flip the model without making a new animation for each animation that's just facing the other way?

real blaze
floral marten
#

submitted a bug report now bc this is clearly not intended behavior catnod

sage radish
floral marten
#

my workaround for now is to just not use the SetInt parameters, and only use buffers

#
public class CompyootShader<P> : IDisposable where P : unmanaged {
    public readonly ComputeShader cs;
    private ComputeBuffer @params;

    public CompyootShader( ComputeShader cs, int stride ) {
        this.cs = cs;
        this.@params = new ComputeBuffer( 1, stride, ComputeBufferType.Structured );
    }

    public void SetParams( int kernelIndex, P newValue ) {
        @params.SetData( newValue, 0 );
        cs.SetBuffer( kernelIndex, ShaderProps.PARAMS, @params );
    }

    public void SetBuffer( int kernelIndex, string property, ComputeBuffer buffer ) {
        cs.SetBuffer( kernelIndex, property, buffer );
    }

    public void Dispose() {
        @params?.Dispose();
        @params = null;
    }
}```
#

and then you use it with a struct for your params (the <P> above)

struct SelectionParams {
    public const int SIZE = sizeof(uint) * 2;
    public uint boxAction;
    public uint frameId;
}```
#

so then before dispatch, you do

cs.SetParams( 0, new SelectionParams() { boxAction = (uint)action, frameId = frameid } );```
earnest heron
sage radish
#

At least, I think that's what you mean by twist

wet sail
#

anyone knows how fast is animation retargeting in unity ? (in ms on avg?) or if i can debug it ?

earnest heron
sage radish
#

Part of it is probably the motion of the rod. In the RDR2 clip, it looks like it's at more of an angle, whereas in your clip it's pretty straight.

earnest heron
charred drum
#

Hello, so I have a view direction, how can I convert it so it can work with raycasts? View direction as in x = -90, 90 and y = -180, 180

tall ferry
frozen ravine
#

actually I've tried scaling both the parent and an empty parent to it and neither worked

#

I figured it out, I had to scale the parent of the rig, not the whole thing

orchid cedar
worldly pecan
orchid cedar
#

I was under the assumption that if I had something like meshes that have a static world position, it's entirely possible to upload the params from the CPU to the GPU once, and then they'd continue to be there (ie, render in the correct position), so something like grass would be a good use case for Graphics.RenderMeshIndirect

worldly pecan
orchid cedar
#

I figured. I just can't seem to get it to work (hince the code dump). RenderMeshPrimatives at least doesn't have the 511 instance limit Graphics.RenderInstance does, but I hope to migrate it at some point

calm moss
#

Hello, I came across this tube renderer script on Github and it works just like I wanted. It's basically like a line renderer but it generates a tube mesh instead. The problem is there's a comment that says that the script causes a memory leak, I have no clue on how to deal with that and I need some help on making the code better

Code: https://gist.github.com/mathiassoeholm/15f3eeda606e9be543165360615c8bef

upbeat path
#

There is no memory leak, the term is being used incorrectly. One thing I would do is to remove lines 42 and 43

floral marten
# calm moss Hello, I came across this tube renderer script on Github and it works just like ...

not sure what @upbeat path means because there are two types of memory leaks in that script, yes!

  1. on line 83, 122, 142 and 192, new arrays are allocated on every call, which puts a ton of pressure on the GC. One way to resolve this is to use persistent List<T> instead that are cleared and re-used, instead of recreated on every call
  2. new Mesh() is used with [ExecuteInEditor] which means that any meshes created will not be automatically cleaned up, and might even get saved to the scene, which is a different type of resource leak. This can be avoided by setting hideFlags on the mesh, like new Mesh(){ hideFlags = HideFlags.HideAndDontSave };
#

unrelated to memory, running the mesh generator in Update() is generally not a good idea either, because you'll be paying that cost every frame, not only in-game, but also in editor

#

generally you'll want to only regenerate the mesh when it's either non-existent, or has changed

sage radish
floral marten
#

but that happens when leaving play mode right? so it's less egregious at least

sage radish
#

Hmm, either that or next time you enter playmode, but if your game mostly happens in one scene with no scene loads, those objects will stick around forever unless you Destroy them yourself or call UnloadUnusedAssets.

#

I guess I meant "in build" instead of "in play mode".

#

The most common case where this happens is when using Renderer.material, which creates an instance the first time it's accessed per renderer, but Unity never destroys it except during scene load!
https://docs.unity3d.com/ScriptReference/Renderer-material.html

This function automatically instantiates the materials and makes them unique to this renderer. It is your responsibility to destroy the materials when the game object is being destroyed. Resources.UnloadUnusedAssets also destroys the materials but it is usually only called when loading a new level.

upbeat path
floral marten
#

alright! well, most people I've been around have never used the term in that super strict way

sage radish
eager mesa
#

currently i'm trying to render a lot of foliage using DrawMeshInstanceIndirect for android platform. when i'm using vulkan api, it works fine. but when switching to OpenGLES3, it doesn't works at all. what is it that i'm doing wrong?

floral marten
real blaze
#

there's also a built-in CollectionPool that can help remove nuances with caching lists in the field section. ensure to Release it after use.

tropic stag
#

Random question, I have a bunch of characters that all have the same script calling Physics.OverlapSphere(), I can change it to OverlapSphereNonAlloc and add a buffer for Colliders. Since unity is single threaded, can I make that Collider array static and shared between all the instances?

flint sage
#

Jus tdon't use it in coroutines

#

Or any other delayed execution

tropic stag
#

I won't but I thought coroutines (at least the monobehaviour one) is still on the same thread?

flint sage
#

Sure but it's delayed, so if you invoke overlapSphere, then wait until the end of the frame, other instance might've ran and updated the data

lucid crane
#

It is safe to do though, I am pretty sure at least. Just performance may suffer.

sage radish
#

No, the data would be different. Performance is the same, the coroutine would just be working with the wrong colliders.

#

But as long as you don't yield between the overlap and processing the colliders, there's no chance of issues.

lucid crane
#

Ah okay. I don’t use coroutines much. 😅

tropic stag
#

oh, yeah, I misunderstood you meant delayed calling the overlap, I'm going to process the results immediatelly after the Physics.*NonAlloc call, thanks!

lament salmon
#

Not sure how to differentiate which hit belongs to which overlap though 🤔 Gotta look into that

#

Ah nvm, the doc explains it ofc

tropic stag
#

oh, I didn't know about that. Definitely not need it now though 🙂 (probably don't need the results buffer static really, it was more making sure I understand it correctly

finite pond
#

is there any way to have custom player loop sub systems show up in the profiler window?

#

im having great success with optimization using the PlayerLoop API, but i'd like to know how much time it actually saved and still takes

#

unfortunately, none of the sub systems show up by default

sage radish
finite pond
#

ahhh, perfect! thats it

sage radish
#

You can nest them as often as you want to see more detailed timings.

finite pond
#

appreciate the quick help!

calm moss
floral marten
calm moss
tropic stag
#

Is there a version of Vector3.Slerp that allows to define the plane in which the vectors interpolate? (I'm switching characters look at vectors and to prevent head snapping I'm trying to slerp the look directions, most of the time it works exactly as expected but sometimes the look at target will fly in an arc above my character instead of in front of them)

#

(just noticed this comment in the docs example: // move the center a bit downwards to make the arc vertical so I think this was happening because I was using the characters transform position as the starting point for the vector directions.

compact ingot
sly grove
tropic stag
#

I ended up using this Vector3 directionSource = new Vector3(transform.position.x, (0.5f * (targetPos.y + oldTarget.y)), transform.position.z); as my vector origin, this would fail with the character being exactly between 2 targets, but I only allow targets within a certain Fov, so it shouldn't happen.

sly grove
tropic stag
#

hmm.. my thinking was if the new POI look target is somewhere high above this will give me an arc upwards, where as if I projected the vectors I'd need another transition from the projected view direction to the actual view direction

azure meadow
#

can I create my own message thingy in monobehaviours without polymorphism?
lemme explain.
I want to add a method to my monobehaviours that is like Update or Start or Awake, that is, called automagically by something else but I don't really know how would I go about it 🤔
I don't want to make my MonoBehaviourWithExtraMethod class, I want it to work with any Behaviour out of the box 🤔
is there a way to see all behaviours ever in the scene or something? 🤔
I feel that if this exists, it's something low-level-ish 🤔

#

interesting... it seems gameObject.SendMessage is the thing...

#

now... how do I see every object in the universe 😛

compact ingot
azure meadow
#

that makes sense! Thanks! 😅

#

At this point, I think that FindObjectByType can eat an interface and find me behaviours... so I might ditch the message system... 🤔
But this has been really useful! thanks ❤️

sweet niche
#

If you open your own docs link, you can even see they recommend using FindObjectsByType instead 😄

upbeat path
granite flax
#

Does anyone ever worked on a full body fps controller? if so I need help

true grove
#

Hi there im newish to unity jsut play around as much as i can why i wait for my other dev to do stuff ive come up with a idea for my game and wanted to know if there is any thing i need to install to make steam dlc work with my game so if i download one dlc and then get another dlc the game would pick up what i got and turn them both on at the same time. I hope someone can understand what i mean as i am dislexic and find it hard to say what i mean

fast egret
fast egret
floral marten
#

I'm aware it's not technically a memory leak yes c:

worldly pecan
#

It's still being managed by .NET

#

You can get a memory leak through allocating in unmanaged memory, *or circular references, otherwise it's very hard to

worldly pecan
#

GC will not clear your memory leaks, but it will free your list if you stop referencing it

untold moth
# worldly pecan Note, memory leak doesn't mean you're forgetful and keeps growing, it means ther...

There are several definitions of a memory leak. Wikipedia for example says:
"In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations[1] in a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code (i.e. unreachable memory)."

I prefer to refer to the first one as a functional leak and the second as an actual leak. In the end, both have the same outcome, so why not call it the same for simplicity?

worldly pecan
#

You can refer to it however you like ig, in my experience most people refer to actual unreachable memory as a memory leak, but if you say functional leak you can probably get your point across better.

untold moth
worldly pecan
untold moth
frozen ravine
#

How would you set up a camera stack like this?

  • Layer with post processing
  • Layer without post processing
  • Layer with post processing
#

I have this setup in my game with 3 layers

  • Background/Everything else besides the player and UI
  • UI
  • Player

I have it set up with a camera stack so the player is always on top of the UI

#

but the problem is that whenever I try using my post-processing, if I only use it on the main camera, it affects everything except for the player, but if I put it on the player camera, since it's above the UI camera, it puts it on the UI which I don't want

#

is there a way to make the UI unnaffected?

#

first pic: only on main (non-player or UI) camera
second pic: only on player camera

#

you can see that the first pic is problematic because the player looks bad without the post-processing and the second pic if problematic because the post-processing gets applied incorrectly and it's affecting the UI

thin mesa
#

this isn't a code question. but if you just want the player on its own to be rendered above the UI but still have it and everything behind the UI affected by PP you could have the player camera render to a render texture that you display in your UI

frozen ravine
#

whoops, where would I put this then?

#

also I was kinda thinking that but I hate messing with render textures lol

thin mesa
coral citrus
#

heya, can anyone see a reason why the above DrawProceduralIndirect would not work, but the below DrawMeshInstancedIndirect does?

vital fossil
#

Respected,
I want to make a car racing game, but I am confused about the AI cars, can I use RCC plugin with Machine learning input and how?
Or any other alternative way?

cold ravine
vital fossil
#

if i want that some car hit the player car after some distance and some focus on the destination..

cold ravine
vital fossil
short junco
#

Hey all, when i create ListView in editor i give a List in a Scriptable Object as a item source.

The problem is when Bind elements invoked the added elements coming null in bind action.

I mean when i query the scriptableObject.SomeList[bindIndex] it returns null but i checked in debug mod the data is created and its valid in SO ?

What can i do i tried override listViewController and added two new action onItemsAddedBefore , onItemsAddedAfter then i call refreshAlItems or Rebuild after onItemsAddedAfter but still comes null ?

Should i markDirty and save asset in onItemsAddedAfter action or what can i do 😄

dusty wigeon
#

@short junco

If you are creating assets, I would expect that you need to actually create the assets, not really on the built in Add function

misty glade
#

Just a random note because it cost me quite a bit of time chasing my tail.. Don't forget that IEnumerable.Append() doesn't modify the original list, but instead returns a copy of the list with the new item appended. Use Add(). 🪳 🪳 🪳

#

(have been writing too many tween sequences and Append()-ing tweens, and was stuck for a while wondering why something else wasn't working.. because I was appending items to a list.. which was showing up with 0 elements when it came time to consume the list)

fresh salmon
#

Yeah it's LINQ, it returns a new instance and is evaluated lazily

scenic forge
#

Less so "a copy of the list," but more it returns a new enumerable where it goes through all items of the list first, and then the appended item.

fresh salmon
misty glade
#

Yeah. It just... surprised me, I expected it to work like Add(), I was chasing 'the wrong thing' wondering why it wasn't working.. I had a lambda that was creating this list and I was thinking the items inside were going out of scope (which is why it wasn't working)

dusty wigeon
#

LINQ is base on functional principle, it is what you really should keep in mind.

misty glade
#
        MessageBroker.Default.Publish(new MyStruct
        {
            OnStart = () =>
            {
                List<CommandBase> storyCommands = new()
                {
                    new Thing(...),
                    new Thing(...),
                    new Thing(...),
                    new Thing(...),
                };
            }
        });

This worked, but then when I needed to conditonally add an item to "storycommands" i refactored to:

        MessageBroker.Default.Publish(new MyStruct
        {
            OnStart = () =>
            {
                List<CommandBase> storyCommands = new();
                storyCommands.Append(new Thing(...));
                if (something)
                {
                    storyCommands.Append(new Thing(...));
                }
                storyCommands.Append(new Thing(...));
            }
        });

it suddenly stopped working.. and I was thinking it was something related to the lambda

#

Not my use of Append() which is.. what the actual problem was :p

dusky lynx
#

hi guys i have an issue with an enumerator that changes my FOV for the player's camera. the problem is that when i call the function to change my fov, when I run it the first time, it changes smoothly, but when I finish (eg. when the player stops wallrunning and the fov needs to go back to the original), it does not change smoothly, it just snaps back instantly. the code is here: https://paste.ofcode.org/385M5nDQfeJuswndPTkvmVm. here's also a video to show what i mean. here's how the function is used in the sliding code as an example:

    if (camFX.defaultFOV < 120f) { camFX.ChangeFOV( camFX.defaultFOV + extraCamFOV); }
    // when I finish the slide
    camFX.ChangeFOV(camFX.defaultFOV);

i didn't know if this was counted as an advanced problem, so I put it in here

misty glade
#

I'd probably actually suggest using Cinemachine for this type of stuff, there's a bit of a learning curve but you'll have a much easier time with camera switching with it

dusky lynx
#

i have cinemachine already

#

thats the problem, before I used DoTween for this but now it doesnt work because of cinemachine

misty glade
#

oh, then just... make one fov camera that's 120, and one that's the default (90?) and just setactive() the camera you want

dusky lynx
#

yeah but the problem is when the user selects a different default FOV

misty glade
#

this will be much simpler.. all you do is set the camera active (and the other inactive) for the camera you want to blend to.

dusky lynx
#

for example if i want to set my default fov to 100 in settings, it becomes a bit of a mess

#

the problem with my original camera system was that it was lagging really hard which is why i switched to cinemachine - I used DoTween on the original one with cam tilt on wallrunning and fov change as well

misty glade
#

I didn't see the video, that you had cinemachine.. so.. make two cameras, one for FOV120 and one for FOVDefault (90? 100? whatever the player wants in the settings) and then when you start the slide:

public void StartSlide()
{
  FOVDefault.gameObject.SetActive(false);
  FOV120.gameObject.SetActive(true); // cinemachine does all the magic for you
}

public void EndSlide()
{
  FOVDefault.gameObject.SetActive(true);
  FOV120.gameObject.SetActive(false);
}
#

doing it with DT is fine but is gonna be a lot more work .. whenever an action starts/ends you're gonna need to check if the tween is running and kill/complete it accordingly

#

the pattern I use (almost everywhere) for doing stuff in DG is to save a reference to the sequence tween and if it gets restarted/ended:

if (_someSequence?.IsActive()==true) _someSequence.Kill(); // or .Complete() if you need OnComplete() callbacks
dusky lynx
misty glade
#

don't mix dotween camera stuff and cinemachine, you're gonna have a bad time imho

dusky lynx
#

so no dotween

misty glade
#

just make one camera for each different ... "camera" (whether that's a different zoom/fov/tilt/etc or an actual different camera view) and then just turn those cameras on/off as you need

dusky lynx
#

ok

#

and do away with the options menu for this setting lol

misty glade
#

cinemachine will take care of the blending for you, and won't be a pain in the jewels when you do things like swap to another camera while a blend is happening

#

you can still have options menu

#

just make it set the options on your "primary" cam

dusky lynx
#

ok ok

#

wait, one question: can I assign a value on the fly on a cinemachine cam's fov, before I activate it, will that work?

misty glade
#

Sure, although if a blend is in progress I'm not sure what would happen

dusky lynx
#

like:

        { 
            defaultCamera.gameObject.SetActive(false);
            slidingCamera.Lens.FieldOfView = defaultCamera.Lens.FieldOfView + extraFOV;
            slidingCamera.gameObject.SetActive(true);
        }```
#

will that work?

misty glade
#

er, yes, but ... that's probably not how you want to do it.. I'd probably just set it (once) at startup and again if the user changes their settings

#

and i'd probably just set it to 120.. if a user wants to play with 120 as the default it's probably going to get weird if you "zoom" to 180 or 150 even

dusky lynx
#

thats the idea, if the fov is less than 120, if its not, it doesnt increase

misty glade
#

just a SOLID principle - your camera zooming should literally just toggle a camera on/off (between zoom and normal cameras), not be mucking with the fov

dusky lynx
#

ok

misty glade
#

set the fov of the "zoom" camera and the "default" camera in as few places as possible so you aren't trying to debug it later and remember all the different places it could change

#

but.. yes, that should work

dusky lynx
#

:dies:

#

cinemachine susness?

dusky lynx
misty glade
#

i'm assuming FOV is a float

#

don't compare floats

dusky lynx
#

yes

#

even if i turn it off it does the same thing

misty glade
#

I'm having a tough time understanding your code - why are you checking the default camera's fov each and every time you slide? i wouldn't do that at all.. just ... start slide = turn on the cam, end slide = turn off the camera

dusky lynx
#

yeah even if i do this it doesnt work

#

commented out

misty glade
#

you can test this out more easily by setting the blend time to like 10 seconds, and then turning on the "slide" camera in the inspector in play mode

dusky lynx
#

i believe this boi might be the problem

misty glade
#

can you paste your entire Sliding.cs to pastebin?

dusky lynx
#

sure

misty glade
#

btw stop comparing floats.. that's not gonna work..

       if (Input.GetKeyDown(slideKey) && (horizontalInput != 0 || verticalInput != 0)) { StartSlide(); }
dusky lynx
#

the problem being?

#

i dont think its gonna work if i comment that out

misty glade
#

you'll have to google up why you can't compare floats, but that's not the problem here

#

the problem is your cameras aren't on the player object, they're just ... floating in space?

dusky lynx
#

so attach the cameras on the player

#

make it a child?

misty glade
#

sliding.cs looks fine but... a couple of things.. if you parent your cameras to the player object (which you should, because you want the camera to be looking out the players eyes, right?) then your sliding.cs StartSlide and StopSlide that change the scale of the object are going to break the cameras

#

I'm not sure what you're trying to do with changing the scale of the player object.. usually you don't want to do that?

dusky lynx
#

umm to slide you have to get smaller

#

how else are you gonna do that

misty glade
#

if you're trying to make your object bigger/smaller (pm.crouchYScale?) then make the mesh bigger/smaller, not the player object

#

thought problem for you: if you parent the camera to the player, and the camera's localposition is (0,0.5,0) (0.5m "up" from the center of the player), then if you make the player scale 50% - the camera will be 0.25m "up" from the center. Maybe that's what you want, though

#

In any case.. parent your cameras to the player, since otherwise you'll have to manually move these cameras around as the player moves around, which isn't something you need to do for a first or second person view

dusky lynx
#

ok

#

i found out that if i use cut instead of ease in out on the cinemachine brain, it works fine

#

thanks for the help

sterile plover
#

One who is generally familiar with C#, which does not concern Unity ?

sterile plover