#archived-code-advanced

1 messages · Page 117 of 1

halcyon flower
#

and this is how i compose movedirection:

#

external strength is just a third vector i add when i need the player to do specific movements, but in 99% of cases it's just vector3.zero

bleak citrus
#

I would suggest not trying to use "x axis" or "y axis"

#

Just make gravity an arbitrary vector

#

You shouldn't need to have lots and lots of cases

halcyon flower
#

the problem is that this is for a sort of level editor, and the user is able to control it by checking and unchecking toggles from an ui, and i also need to remember the gravity axis, so i thought serializing a string "x" or "y" or "z" would have been easier:

bleak citrus
#

ah, I see

#

And I guess you do eventually wind up computing a gravity vector

#

So, the problem is that you're getting a bad forward direction

halcyon flower
#

pretty much yes

#

but only in some cases

#

in a three dimension space there are 24 cases possible

bleak citrus
#

This is tricky because you can't, given only an up vector, consistently choose a forward direction

halcyon flower
#

i thought that too, but then why does it work between -y +y and +x?

bleak citrus
#

I bet it's just right 50% of the time and wrong 50% of the time

halcyon flower
#

wait can i upload the video here?

#

maybe it helps

bleak citrus
#

If you wrote it slightly differently (maybe use Vector3.down when crossing to find a forward direction), you'd get opposite results

#

But yeah, an example of the problem would be helpful

halcyon flower
#

hold on a sec

#

here, as you can see, switching from -y and +y to +x isn't a problem, and neither is switching between x and z, but the problems are with the switches between -y +y and +z, -z and -x, where the player comes out facing the wrong direction

#

i was so done with this i even tried to brute force it, but with no results, the rotations just all become messed up

bleak citrus
#

to make sure I'm following this correctly -- you store a rotationY value on the character

#

and after computing the targetRotation for the new gravity direction, you apply an additional self-space rotation on your Y axis

halcyon flower
#

pretty much yes, the whole movement script is about 1000 lines, so it's hard to narrow it down, but yes

sly grove
#

uhhh this code is probably overcomplicated - i would just be doing vector math and projection based on the surfaces you see - with some raycasts

bleak citrus
#

Depending on exactly how you picked the forward and up directions, the meaning of that extra Y rotation will vary

sly grove
#

And like - this stuff is spooky

halcyon flower
bleak citrus
#

Consider just keeping rotationY at zero and seeing how your orientation changes as you move between surfaces

#

You can also use Debug.DrawRay to visualize the basis vectors -- the "forward" and "up" directions that you're calculating.

#

You may need to recalculate rotationY after this "change of basis"

halcyon flower
bleak citrus
#

comparing for exact equality with vectors is weird

#

It's kind of okay in this case because you only have six possible vectors

sly grove
bleak citrus
#

It does also smell like a "hack", yes

#

a special case where you just give up and use a fixed value

halcyon flower
#

yeah i did that because there's pretty much no way the player will have a gravity different than that

sly grove
#

A better system would be able to handle any angled surface whatsoever which would make this kind of explicity comparison completely infeasible

halcyon flower
#

i only use 6 fixed gravities

bleak citrus
#

I think you need to include your original basis vectors when figuring out the new basis vectors

halcyon flower
bleak citrus
#

you need some extra context here

sly grove
#

sure and that means you need like... 6 if statements? or something?

This can all be condensed

sly grove
bleak citrus
#

you're not just picking a new "forward" and "up" direction in a vacuum

sly grove
#

it's not really that bad!

bleak citrus
#

you're trying to pick directions that are consistent with your original "forward" and "up" directions

bleak citrus
halcyon flower
#

wait lemme give you guys some more insight, because i don't think the round surfaces thing can work in my case

#

i had them set to invisible before, but this is what the room really looks like

#

i don't really care for the player to be able to walk on any wall as they please

#

i just want to create a sort of "Pad" that switches your gravity when you walk on it

#

hence this:

bleak citrus
#

What direction is even the "correct" direction to be facing, anyway?

halcyon flower
#

that's the problem

sly grove
bleak citrus
#

If you're facing the +Z direction, and you change gravity so that +Z is now "down", you're now starting straight into the floor

halcyon flower
sly grove
#

As for the facing direction you could take a vector 45 degrees up from your current forwrad direction and project that on the new surface

sly grove
#

You want to walk on the pad

#

no matter what its orientation is

#

if not - then you'll be clippign through it?

bleak citrus
#

I wonder if you can use Quaternion.FromToRotation here

sly grove
#

Which sounds worse

bleak citrus
#

Find the rotation between the two gravity vectors, then apply that to your original forward and up vectors

#
Quaternion delta = Quaternion.FromToRotation(oldGravity, newGravity);
Vector3 forward = delta * transform.forward;
Vector3 up = delta * transform.up;
transform.rotation = Quaternion.LookRotation(forward, up);
#

The behavior would get weird with a perfect 180 degree shift in gravity

halcyon flower
#

where would this go in my code?

sly grove
#

I would just be doing something like:

Vector3 forwardAndUp = transform.TransformDirection(new (0, 1, 1)).normalized;
Vector3 newForward = Vector3.ProjectOnPlane(forwardAndUp, newSurfaceNormal);

Quaternion newRotation = Quaternion.LookRotation(newForward, newSurfaceNormal);```
halcyon flower
#

im sorry guys im just way stupider than you two hahaha

bleak citrus
#

I'm guessing it just happens to be correct sometimes and happens to be wrong sometimes

#

That tends to happen whenever you use a fixed axis, like you do here

halcyon flower
#

i honestly got not solid knowledge about what vector3.cross does if i have to be honest

#

i just read the documentation and it sounded like the solution to my problem so i just went with it

bleak citrus
#

It finds a vector that is perpendicular to two other vectors

halcyon flower
#

i don't even know if normalizing it has any sense or not

bleak citrus
#

Once you have two valid basis vectors, you can cross them to get a third vector

halcyon flower
#

could it then be that in some cases the vector is not valid?

#

i mean if you have two random vectors does a cross one always have to exist?

bleak citrus
#

Two parallel vectors don't have a meaningful cross product

#

However, that's probably not happening here

#

It's just that there are two outcomes

#

depending on the relative orientation of the two input vectors

halcyon flower
#

got that, thank you both for your time and have a nice day!

old swallow
#

Is there a way to check Shader compile errors from other platforms. I have a Shader that compiles on Windows editor and build but is pink on Android. Probably just something that is not supported on Android. I just cant get any errors in the console even when connected.

haughty saddle
#

Mathematics.math.pow() outputs NaN when power is not a round number. I compile it with Burst.

I've tried to update to the latest Burst version, but got the same result.

Any ideas? 🥲

sly grove
haughty saddle
#

Yep, managed to reproduce this. I get NaN when:

  • value is negative
  • power is not a round number
sly grove
#

but it kind of makes sense

#

because let's say you are raising a negative number to the power of 4.5

#

That's like n^4 * n^(.5)

#

n^(.5) is an imaginary number if n is negative

#

(since that's the square root of n)

#

So it's not a bug. The answer is a complex number, which obviously doesn't fit in a double or float

misty glade
#

i is a number to mathematicians, but not to programmers using primitives :p

bleak citrus
#

Yes, that's the right behavior

haughty saddle
#

I think i could just 1.0 / pow(abs(x), y) and get what i need?

sly grove
#

for example:
(-2)^2 is 4
(-2)^3 is -8
What are you trying to get for (-2)^2.5?

#

What's the use case here?

haughty saddle
#

Yep, that does not work

haughty saddle
#

power is a parameter you can tune

misty glade
#

you don't wanna just constrain that parameter to non-negative bases?

sly grove
#

is the base the distance? Negative distances don't make sense

misty glade
#

(or even if not, just wrap the pow() call in a try/catch and set it to 0/1, or whatever makes sense for your usecase)

haughty saddle
misty glade
#

i mean, smarter people than you or me struggled with "what's the square root of negative 1" for a lot longer than an afternoon before coming up with complex numbers

#

I wouldn't call yourself cooked yet :p

haughty saddle
upbeat path
nova cypress
#

How can i change the Texture of a Specific Face and get the Texture of a Specific Face of a MeshRenderer?

bleak citrus
#

I don't really understand what you're trying to do here

#

Are you trying to do per-vertex lighting, maybe?

nova cypress
#

I have no idea what that is, i am just trying to get the Texture that gets displayed on a face. I know that faces do not have Texture properties but i mean just getting from for example 4 vertices the face, and from that face the UV data and then translate the UV data to the Texture and then transform that into a Texture

bleak citrus
#

Explain your actual objective here

#

not "get the textures on a face"

#

What is the longer-term goal here?

nova cypress
#

Im trying to remake Source Engine Lightning, where each Face's Texture is either Darkened or Brightned based on the conditions. For now i just wanna be able to modify the Faces themself.

bleak citrus
#

that's how all lit rendering works

#

perhaps you actually want to write a shader...?

#

you're going to need to show an example of whatever it is you're trying to create

nova cypress
#

Okay hold on

#

Lightning like this (Only the Cube)

bleak citrus
#

This looks like a normal lit shader

#

It's getting lit by a sun light from above (hence the shadow) and is also receiving ambient light

nova cypress
#

Hmm i though Unity had really good lightning which doesnt affect the entire face, thanks i guess.

bleak citrus
#

Well, yeah -- if you shine a light onto the object, you'll get per-pixel illumination

bleak citrus
#

That's a common technique for games that want to look really old

nova cypress
#

ahh

bleak citrus
nova cypress
#

oh

lament salmon
#

Maybe you are thinking of flat shading? 🤔

#

Like sharp edges that are the result of not sharing vertices between faces

bleak citrus
#

yeah

nova cypress
#

Seems like it

bleak citrus
#

This cube's faces don't share vertices, and you get sharp edges as a result

#

that's a property of the model itself

nova cypress
#

oh nice

lament salmon
#

If it did share vertices it would be shaded like a sphere

#

So this is common

nova cypress
#

Okay thanks ill keep this in mind!

lament salmon
hollow dust
#

can someone help me with this error

untold moth
pliant cypress
#

I'm gonna forward this again. I started to think that source generators in unity are bugged with namespaces. But, I can create a test class, and put it in a namespace, and it'll be recognized fine:

namespace Example
{
    public class Test : NetworkObject
    {
        ...
    }
}
pliant cypress
#

I FIXED IT.
It was because the generator was being applied to not just the main project, but 2 other projects, which I don't know what they are. As a result, the proxy factory was being generated for projects that didn't have the owltree code like the main project does. My solution was to not make an empty factory if there's no classes to make proxies for.

raven bolt
#

'Nother question:
Working with textures. I need an atlas that I can add to during runtime, but generates mips too. Not sure if the atlas approach (8192x4096) or tex2DArray (512x512x100) is better.

The atlas would be initialized all at once at resolution with unfilled areas being black until written to. Not sure how the tex2Darray should be handled (is resizing costly?)

vague bear
#

can someone help me make a system to save a list in unity for my VR cosmetic system

#

dm when you can

untold moth
raven bolt
# untold moth There's no such thing as resizing a texture. It's basically destroying it and cr...

i was only thinking of "resizing" the array. If the textures are stored on the CPU side and GPU side, then i can recreate the larger GPU array only as needed. Yes its computationally expensive, but occupied less VRAM when the player doesn't need it.

if its gravy either way then i guess i'll go with whichever way is easier/faster to write. Im thinking the Texture 2DArray. Any input there?

untold moth
raven bolt
#

still trying to determine if an 8192x4098 texture is too massive and instead should go for 2048x textures and have multiple materials

#

benchmarking the performance oon this is a bit tough at this stage in development

untold moth
raven bolt
#

PCs standalone, multi OS

untold moth
#

Then a bigger texture is probably better than several snaller ones.

#

Mainly the mobile platforms are the ones having limitations.

raven bolt
#

yeah, partly the reason i avoid them altogether

#

plus my ideas dont really scale well too mobile as theres an assumption for online integration

#

cant network for my life

#

anyways, thanks for your help!

dapper cave
#

CullingGroup.GetDistance returns a band index that doesn't match the distances I set it at. LOD bias is set to 1 so there should be no offset. Anyone had that and fixed it?
What I'm doing:
I inject in the cullinggroup distances: 7,17,116 (different values in the video)
at 60 it switches from band 2 to band 3. culling uses the sphere's closest to camera but the sphere is at most 1.6 unites big so this isn't it
sphere is updated in lateupdate by changing the boundingsphere[0].position and radius directly, instead of recreating a BoundingSphere (which is weird because i thought that struct didn't allow that...)

native beacon
nova cypress
#

Oh they did? Where could i find it?

native beacon
#

It has been years since I saw them, so not sure where you could get them now.

nova cypress
#

Alright ill look, thanks!

bronze glen
#

I want to check if any of the UI buttons on canvas is highlighted, is there an efficient way to do it without adding script with update function to every button?

bronze glen
#

when unity uses Highlighted Color on the button

compact ingot
#

you can check if the EventSystem’s raycast hit is a button and the child transform of the panel’s root transform.

bronze glen
#

hmm, yeah, I think this makes sense, but it will need additional checks, though i think this is fine

#

thank you

native beacon
#

In a structure of nodes which have links to other nodes, what is the best/fastest way to determine connectivity between two given nodes? Essentially pathfinding but without concern for cost, shortest path, etc. but just 'does a path exist?'

bleak citrus
#

If you don't have any extra constraints, you must search the entire graph

dusty wigeon
bleak citrus
#

If the graph isn't constantly changing, then precalculation sounds like a great idea

dusty wigeon
#

It really depends on the context.

bleak citrus
#

You can preprocess the graph to find every connected component. If two vertices are in the same CC, there is a path

native beacon
#

It won't be constantly changing, but it will be changing- generally in response to player input

bleak citrus
#

In that case, you can recompute the set of connected components after the graph is dirtied

#

If you're just adding or removing single edges at a time, you can probably do a little better than complete recomputation

native beacon
#

And if I can limit it to removal?

bleak citrus
#

I have a similar problem in my game. I have a graph of Contexts between which sound and visuals and be exchanged (think of how you can't see past a closed door, but you can hear muffled sound)

bleak citrus
# native beacon And if I can limit it to removal?

You can find the "min cut" between two sets of vertices, such that they get split into two separate components if those edges are cut. But if you don't have any sets of vertices to calculate that for, it wouldn't help much

native beacon
#

Hm. So at least this should help the search... looking for pathfinding implementations was... less helpful. :D

drifting solstice
#

precomputation just moves that work somewhere else and caches it

#

then you just have to be as clever as you want to be with the cached data

native beacon
#

Yeah.

#

Well, still glad I asked :D

slow jay
#

how to make sure that my game doesn't allocate too much memory for NativeArrays? do I have to explictly make sure that some limit isn't exceeded, or will the Unity engine make sure that the game doens't crash because the Player allocates too much memory?

upbeat path
slow jay
#

but I can't limit it based on the amount of meshes selected, because it depends on the amount of vertices instead.

upbeat path
slow jay
#

is there a way to check how much memory the user's computer has, and then set a limit based on that?

#

or does it make sense

upbeat path
#

there is but then, again, you're going into Native OS code. Best is just to select an arbitrary constraint, maybe in some kind of setting so it can be user adjusted

#

then the onus is on them if they want to play silly buggers

regal olive
#

Does changing method from non virtual to virtual causes breaking changes to previously compiled code?

echo coral
regal olive
#

No, but im making a library and was thinking how to model it in such a way that it is backward compatible

echo coral
worldly pecan
worldly pecan
bleak citrus
pure frigate
#

hi, do people know how do AnimationClips work under the hood?
how is the AnimationController able to change properties on game objects by just knowing the property name?
it can't be using reflection, otherwise these animations wouldn't work on AOT compilation

sly grove
#

The only thing you can't do really Is Reflection.Emit

pure frigate
#

oooh

#

I was under the assumption reflection was impossible in AOT

#

thanks!

final steeple
#

Unity also stores its own type information (known as the "type tree")

#

That's what it uses for things like this (the type tree also handles things like native fields, i.e. stuff not defined in C#)

sly grove
honest bear
#

Hello, is there a dedicated channel for graphics programming (ie custom render pipeline stuff and not just shaders) or should I ask my questions here?

compact ingot
honest bear
#

alright, thank you

shadow plover
#

hey guys, im trying to make a procedurally generated island, and i followed sebastian lague's tutorials up until episode 11 for the falloff maps since i didnt need anymore, but the terrain color is really blocky and pixel-y and i was hoping someone could help me make it more realistic

lament salmon
bleak citrus
#

(point to bilinear, that is)

shadow plover
#

how would i do that

bleak citrus
#

this is a property of the texture itself

#

however, we don't really know how you're rendering this thing right now

shadow plover
bleak citrus
#

what is actually happening here? did you generate a big mesh? how are the colors being applied?

#

I see you have a color fo reach kind of region

#

so i'm guessing there isn't a texture at all

lament salmon
#

Is it all done in a shader?

shadow plover
bleak citrus
#

that doesn't tell us very much...

shadow plover
#

i mean

bleak citrus
#

I'm taking a shot in the dark and guessing that this generates a bunch of small quads and uses vertex colors to give them a color

shadow plover
#

yes yes thats how it is

#

well

#

triangles

bleak citrus
#

if so, you need to find a way to actually blend the colors together

shadow plover
#

not quads

bleak citrus
#

e.g. by setting the vertex color based on the average color around that vertex

#

instead of using just a single color

shadow plover
#

how though?

#

like through a shader?

bleak citrus
#

that would be too late!

lament salmon
bleak citrus
#

when you generate the mesh, compute vertex colors based on the average color of all of the tiles near you, rather than just your tile's color

lament salmon
#

Watch a bit from that timestamp. He deliberately uses Point filter mode to make it look more "crisp"

bleak citrus
#

oh, so this is using a texture

#

not vertex colors

shadow plover
#

you can still see the quads in between

lament salmon
#

Not sure what you were expecting then

bleak citrus
#

yeah, that's inevitable if you have a single huge texture

lament salmon
#

Maybe you just want more dense pixels

#

Higher resolution

bleak citrus
#

If you want completely crisp edges, you'll need to generate a mesh that follows the contours

#

or something more elaborate like that

lament salmon
#

The coastline would be less blocky if you made the water a separate object

#

Just a simple plane at water height

shadow plover
#

yea ik i already have water

#

i just hid it for now

lament salmon
#

What does it look like now?

shadow plover
lament salmon
#

Right. You need to either use higher texture resolution or do something like what Fen suggested

shadow plover
#

huh okay

#

ty

bleak citrus
#

You could also blur the texture yourself

#

That'd help to cover up the problem

shadow plover
#

how?

bleak citrus
#

I bet there is a library for applying things like blurs to textures

lament salmon
#

A box blur is pretty simple to implement. Gaussian is almost as simple, but gives better results

#

The idea is to loop the neighboring pixels and get the average value

bleak citrus
#

notably, you can do an expensive blur once when creating the texture

#

instead of doing it in the shader, which can get very silly very quickly

#

(i'm trying to implement my own bloom effect for a VRChat avatar and it's going great)

scenic forge
#

Additionally you can approximate Gaussian blur with multiple box blurs for better performance.

bleak citrus
#

want four grab passes?

lament salmon
#

Or something different

scenic forge
#

Yeah that one.

bleak citrus
#

That's not a box blur!

#

at least, it doesn't have to be

#

you can separate a Gaussian blur into its vertical and horizontal components

#

doing them in sequence is identical to sampling the entire square

scenic forge
bleak citrus
#

ah, I see

final steeple
#

You can technically use the type tree API from C# but it requires native interop with the engine. It does allow you to do some cool stuff in a build that you otherwise couldn't though

misty glade
#

So, I'm doing some UI stuff and rendering some HP bars in the UI layer. I have a dictionary of them, tied to the renderers (gameobjects) in the game. I iterate these sliders in LateUpdate() and update their position based on camera.WorldToScreenPoint. It "works" but it's a smidge behind - like it feels a little sluggish like it's "catching up" to the camera. It's not bad, but I'd like it to be crisper and really track the camera movement perfectly.

I'm using cinemachine's CinemachinePositionComposer and CinemachinePanTilt but I'm only mucking with them in Update(). Cinemachine is set to update in "SmartUpdate". Anyone have any guidance here? I can't seem to find how I should set cinemachine's update or update my slider's position. TIA.

#

It's probably hard to see but that "2/5" slider is a few frames behind the camera when I drag the map around

#

Should I maybe just jam my script that's handling updates at the bottom of the script execution order? I suspect that cinemachine's "blend update method" of LateUpdate is sometimes(?) getting called before/after my script

austere jewel
#

Either that or take control over it yourself and set the update mode to manual

misty glade
#

Hm... I thought I tried this previously, but just changing the blend update from LateUpdate to FixedUpdate resolved it and it doesn't seem like there are issues with pan/tilt/position blending...

(having one of those days where I swear I tried something and it broke for some reason so I left it alone)

#

Now I have to consider whether I wanna keep this approach.. since on one hand, the sliders are nice and legible no matter where the units are, but on the other hand, they seem to get bigger/smaller as you move around..

#

Oh well. Good enough for a demo. Resolving the task. :p

thx vertx

bleak citrus
tired fog
#

Is there any way to intercept a depth buffer texture? I'm implementing a depth based occlusion algorithm that i think would work nicely if I could render only items in the default layer on the depth then apply occlusion culling for the next vegetation rendering steps

#

Basically my issue is that occlusion culling with lots of vegetation is a bit of a pain since a tree can have branches and trre trunks behind it partially rendered and i dont want items from the same draw call to be used when checking the depth buffer

dusty wigeon
tired fog
dusty wigeon
tribal flint
#

Can someone help me figure out why mouse input is not working with new input system. i tried mouse and keyboard input .

#

someone can you help me to figure it out

sly grove
tribal flint
#

ok thank you

timid orchid
#

So lets say that my character has a rigidbody 2d that gains velocity when I jump, and gains negative velocity when it falls in respect to the Y axis. I have a sprite sheet of 12 jump/fall frames that I want to dynamically assign different velocities for. I do not want an animation of the jump/fall in the animation controller, because it interferes with other mechanics I coded in. The solution I want is to change the sprite of the character depending on the velocity of the rigidbody 2d.

https://www.youtube.com/watch?v=kmRUUK30E6k&t=363s
if you look at this video at around 5:30 it gives the theory behind the code, but not how to implement it per say (Helpers.Map doesnt exist in the unity libraries and i have no idea how to code that) he does a way better job of explaining it

any help plz

Hey Pals! BIG Upload from me this time. This is the first time I really go into detail about more technical animation methods that span Aseprite and Unity, and I've never uploaded anything about jump animations, so here we are! It was super challenging knowing how much depth to cover, so let me know if there's anything you want me to clarify or ...

▶ Play video
regal lava
pearl mortar
#

I have a code structure question I'm struggling to find a good answer for.
I'm working on an RPG, I have a scriptable object Item that holds all of the basic item stats.

When it comes to looting I have a LootTable and LootableItem that inherit from a LootableObject that in turn inherits from scriptableObject. I'm not quite sure how to link these two up in a way that wont pollute my editor with a ton of scriptable objects though.
I really need LootTable to be a scriptable object, I don't really want LootableItem to be scriptable though.

#

My initial idea was to use an interface for LootableObject but because that's what's serialized I wouldn't be able to reference and assign values in the inspector which I really want.

regal lava
#

You can serialize prefabs onto scriptable objects just fine

dusty wigeon
trim void
#

has anyone worked with ScriptableObject?

half swan
trim void
#

so i had this problem since 1month and i cant fix i have code where car can change styles in game everything was working perfecly(logic has no prolem) and one day when i save code everything changed and now when i am setting clone of style its giving me error that it doesnt exist ,also the buttons for changing car style doest cloning heres code:

trim void
# trim void

and in here its giving me error at this line: public static bool StyleIsBought(LockedContent obj, int index)
{

    return PlayerPrefs.HasKey(string.Format("{0}_{1}", obj.Car.AvailibleStyles[index].Styles.name, C.Bought));
}
trim void
# trim void

and this is where i am making styles with their logic

#

with instantiane a buttons for changing styles

#

i really cant find any error or mislogical line in my code

untold moth
# trim void

First, start from sharing !code properly. Your scripts qualify as big blocks of code.

thorn flintBOT
untold moth
zealous onyx
#

What is with Untiy Physics (ECS) rigid objects accelerating on slopes / ramps? is this normal?

plush hare
#

and/or any other mainstream physics engine for that matter.

sly grove
mortal birch
#

can someone help me with some bug i'm having with textMeshPro ?

compact ingot
mortal birch
mortal birch
#

here is the code anyway:
https://paste.mod.gg/jwttmrjnurrk/0
i'm trying to combine a typewriter effect with some visual effects on the text the problem is that there is a flash of white when a new character gets written
i tried many things like waiting for end of frame or using LateUpdate but nothing worked

onyx apex
#

hey guys i need some help im trying to bake a navmesh but i need to set the NavMeshBuildSettings ``` NavMeshBuildSettings settings = NavMesh.CreateSettings();

        settings.agentRadius = 0.5f; 
        settings.agentHeight = 2.0f; 
        settings.agentSlope = 45.0f; 
        settings.agentClimb = 0.4f; 

        int agentTypeID = settings.agentTypeID; ``` is  my settings but im unsure how to set them due to there being nothing i can find help? thanks!
still timber
#

Hi guys! Source generator problem:

I have defined an enum named Access in the .cs file in Unity project.

How can I use this enum in my Source Generator code (which of course is a different .NET Standard class library project)?

flint sage
#

Put it in a 3rd project that is referenced by both your source generator and your unity project?

still timber
# flint sage Put it in a 3rd project that is referenced by both your source generator and you...

That's what I was thinking about, I guess I'll have to make another .NET class library project, whose dll I'll have to put into the Assets folder in the Unity project, and for the Source Generator project just give a reference to that dll.
Do I understand this correctly?

Is there any other better solution? Or am I left with just extracting it like this to a separate project (dll)?

I feel a bit silly to make a whole new dll just for one enum, hence I am looking for other solutions 😅

flint sage
#

I don't think there's any other solution

still timber
flint sage
#

You use the roslyn source generator APIs

still timber
flint sage
#

It depends what you're trying to do

#

The roslyn api is more tedious, but it doesn't let you straight up access a type

#

The roslyn API works using the abstract syntax tree of your code, rather then dealing in runtime types

still timber
# flint sage It depends what you're trying to do

What if I had to use RigidbodyInterpolation (enum) in my roslyn source generator? Is Roslyn API the only thing I could use?

It's really limitating that I could not reference UnityEngine.dll in sourcegenerator project ;-;

#

string based approach? like in my SourceGenerator just mimic all RigidbodyInterpolation enum values?

flint sage
# still timber What if I had to use `RigidbodyInterpolation` (enum) in my roslyn source generat...
Meziantou's blog

When creating a Roslyn analyzer, you almost always have to work with types. For instance, you may want to find an argument of a specific type or check if a method is declared on a specific type. For instance, your analyzer may need to answer the following question: What is the type of the sample in var sample = new Test();? Or does the Test clas...

#

Source generator API is similar to that

compact ingot
mortal birch
#

i did try maxVisibleCharacters tho and it didn't fix it

compact ingot
#

it works for all languages that do not make extensive use of ligatures

#

and if you convert your arabic text to actual glyphs (not automatic ligatures) it would still work

mortal birch
#

but sure

#

i will look into it

carmine lion
austere heart
#

This is what my script is referring to.

#

private void OnEnable()
{
}
private void OnDisable()
{
}

#

You've got Activate() and Deactivate()

#

I hope this helps.

old swallow
#

Hay, does anyone have any clue how to implement MSAA using the RenderPass/SubPass system in a custom SRP?

still timber
# flint sage https://www.meziantou.net/working-with-types-in-a-roslyn-analyzer.htm

I tried for many hours and I need to ask for help.

I got managed plugin (dll) with Access enum type defined in it.

In another c# library class project (source generator) I have a reference to the first project or to compiled dll from first project (it doesn't matter). I see Access enum, everything works and etc.

When I copy these two dlls into Unity, I got this error:

Source generator error:
System.IO.FileNotFoundException: Could not load file or assembly 'Polyflair.Codebase.SourceGeneration.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Cannot find a file.
File name: 'Polyflair.Codebase.SourceGeneration.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

Why doesn't it work in Unity? Why source generator doesn't see first project (Common)?

Rest of the Unity scripts can see Access type from Common dll, but SourceGenerator (second dll) doesn't.

still timber
#

Please help some good soul 🙏

scenic forge
#

A bit late to the conversation, so you have an enum from a separate assembly, and how are you trying to use that enum in your SG? Does your SG need that enum to run, or does it merely generate code that needs that enum?

still timber
#

I tried defining reference inside SG.csproj like this (this path is probably stupid):

  <ItemGroup>
    <Reference Include="Polyflair.Codebase.SourceGeneration.Common">
      <HintPath>bin\Release\netstandard2.0\Polyflair.Codebase.SourceGeneration.Common.dll</HintPath>
    </Reference>
  </ItemGroup>

but also like this:

  <ItemGroup>
    <ProjectReference Include="..\Polyflair.Codebase\Polyflair.Codebase.SourceGeneration.Common.csproj" />
  </ItemGroup>
#

Inside SG everthing works perfectly, but when I copy dll inside Unity, I got this error that it can't find Common

still timber
#

This is example code I'm using inside SG, if you want to know 😛

private Access MergeAccess(Access a, Access b)
{
    return CompareAccess(a, b) >= 0 ? a : b;
}

private int CompareAccess(Access a, Access b)
{
    return AccessPriority(a).CompareTo(AccessPriority(b));
}

private int AccessPriority(Access a)
{
    return a switch
    {
        Access.Private => 0,
        Access.Protected => 1,
        Access.Internal => 2,
        Access.ProtectedInternal => 3,
        Access.Public => 4,
        _ => 4
    };
}

private SyntaxToken[] ConvertAccess(Access access)
{
    return access switch
    {
        Access.Public => new[] {SyntaxFactory.Token(SyntaxKind.PublicKeyword)},
        Access.Private => new[] {SyntaxFactory.Token(SyntaxKind.PrivateKeyword)},
        Access.Protected => new[] {SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)},
        Access.Internal => new[] {SyntaxFactory.Token(SyntaxKind.InternalKeyword)},
        Access.ProtectedInternal => new[] {SyntaxFactory.Token(SyntaxKind.ProtectedKeyword), SyntaxFactory.Token(SyntaxKind.InternalKeyword)},
        _ => Array.Empty<SyntaxToken>()
    };
}
#

but it doesn't matter what I do with this, hah

scenic forge
#

Yes that's what I was trying to know, that you are actually accessing Access in your SG code and not just context.AddSource("some C# code here that uses Access");.

#

I haven't done a SG that has dependencies so I'm not sure either, but keep in mind that SG runs in a different context (your IDE runs it to update the generated code, and of course Unity), so you need to expose your Common.dll to that context, which I'm unsure how to do exactly.
You can try setting that dll to be included in Editor, or try giving it the RoslynAnalyzer asset label.

still timber
scenic forge
#

What's the error?

#

If your Unity project also needs Access, then remember you need to have the common available in both contexts. I'm guessing that you got that error because you changed your dll to only be available to SG and no longer available at runtime.

still timber
# scenic forge What's the error?

What configuration do you want?

If Common is plain dll with standard settings, it's not visible by SG and I got the error I pasted above called from SG.

still timber
scenic forge
#

What's the error with the label?

still timber
#

I don't know if that is even allowed (tagging and not excluding platforms).

#

same error from SG:

Source generator error:
System.IO.FileNotFoundException: Could not load file or assembly 'Polyflair.Codebase.SourceGeneration.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Could not find a file.
scenic forge
#

So the issue is still that the SG cannot see the dependency.

#

Welp not sure then.

#

What's the reason that you have Access defined in a shared class library rather than simply inside the Unity project?

still timber
still timber
scenic forge
#

If defined inside the Unity project, SG can still access it (but it will be in source code form so it's less convenient depending on what you want to do with it)

still timber
#

That's the same with enum defined directly in Unity. I cannot use this type inside SG.

scenic forge
#

Sure, you can't use it as a type, but you still have its source code and can do whatever with it, just likely not as convenient.

still timber
vital fossil
#

Respected, our game is live.. and it works fine, code size is optimized.. but everything in the single scene, and the game is increasing rapidly with time.. and our senior manager demands that the game works fine without lag in low end devices.. currently we are using 2023.2.20 unity version... we have also applied occulion culling, also have buttons of low quality, medium, high quality.. changes far, and some others....., which other settings i can use or methods for low end devices... e.g like texture size reduce...

still timber
#

New Input System or Rewired (asset store)

still timber
compact ingot
#

at least via input system you can get all the low level info that the device driver provides, but it can't give you more than the OS/driver provides, so if you specifiy your device too precisely, it will not work when another device is connected (say joystick A vs B) since they usually use different names and IDs internally for their controls. So Input System abstracts that away for you, allowing you, in general, to declare your input in terms of a generic "gamepad", "keyboard", "mouse", "touch controller" etc. But as mentionend, joysticks aren't supported beyond H/V/Twist/Fire 'cause there are just too many variations. However you can specify your own abstraction or allow the users to map their particular device to the actions defined by you.

compact ingot
#

what specific devices do you want to support?

#

so you want to support basically all steering wheels, pedals and shifters? then you have to make that support yourself, like all games that support these devices.

#

yes

#

if you want to spend some monexy, rewired (asset) supports common joysticks/wheels

#

yes

#

how else would they?

#

someone has to create the support, if you have your own engine, thats you who has to do it

#

but as mentioned above

#

you can have the player map their device channels to your actions

#

input system supports that

#

you can "listen" for triggers/axes and bind whatever is actuated to a selected action

#

at the end of the day, its just some manual labour you have to perform. In most cases there is no special magic that makes these work.

inner locust
#

Could someone help me figure out the reason for which Buffer.BlockCopy always writes at the dest array's index 0?
https://paste.ofcode.org/jFA5bfcUH8DTQYjHGbeKW8
Debugged it, and while the offset (actualMessageLength) is 16, the source array is always copied starting from index 0
The intended behaviour is for bytes to be appended to the messageHolder array

steel snow
versed sun
#

not exactly sure where this goes, could go in UI/UX, but I'm trying to make a custom foldout custom inspector but for some reason it only lets me make ones that are frozen open or closed

versed sun
#

thanks

#

doing random stuff I somehow found it out

#

For people who are randomly searching through here I'll just say I solved it by assigning a bool to the foldout

calm dock
#

when i am moving its working and all but when i turn around when i click on w its doing like s and when i click on a its doing like d

drifting solstice
#

you removed the file extension from your attachments...

twilit jetty
#

soo I have 3 global rotations ( quaternion )

Hips
Spine
Chest

I want to calculate local rotation of Chest any easy way?

merry tree
#

I need to determine something that should be simple:

Does my saved code match my assembly, how can I tell from C#? Unity normally handles this automatically, detecting a file change and recompiling and reloading the domain. Unless their is a compilation exception. But there is an edge case beyond this.

For now, I'm using CompilationPipeline.assemblyCompilationFinished to detect when compilation changes come in, and it stores the last state for Assembly-CSharp.dll. Compiled or not. However Unity has a performance improvement that detects if a change brings it back to the same state as the compiled version, probably a CRC comparison. This event doesn't get fired, if the code was broken, and undo the file changes, returning the CS file to its original exact state. A single space being added will trigger a recompile, but removing an extra character that breaks syntax doesn't. (not when it was the only one added)

I have a question with more details in discussion, https://discussions.unity.com/t/how-can-i-tell-if-my-assembly-matches-my-source-code-from-code/1576369
But if anyone knows an easy way to determine if the assemblies match the files without having to force a recompile of everything that would be preferred.

untold moth
#

I think there's not much else to say beyond what has been said on the forums. Compilation is a one way process and there's no mechanism to compare a compiled IL code to C#(aside from compiling it of course).
Most engines that I know compile code in several steps: they compile whatever files they need first and put the results in an intermediate folder. And if the build is successful it then overwrites the files in the actual deployment destination. So, unity wouldn't need to keep a cache of all the code state. It just needs not to replace the active assemblies if the compilation failed.
I'd also note that in most cases compilation of C# in unity is way way way faster than assembly reload and scene reload, which usually come along, but don't happen on a failed compilation afaik. Which is why you might think that unity doesn't compile anything if there's an error.

pastel whale
# merry tree I need to determine something that should be simple: Does my saved code match ...

not sure what you want to achieve by it but here some inshight:

  • the changed file is detected by os file watcher and event is raised, the path of the file is pushed to import queue.
  • next once the Refresh is called (Unity regain focus or manual Refresh is executed) it validate the assets in queue against the entries in Library/SourceAssetsDB if something is different then it goes for next steps, the hash of source asset data is stored in the db, so if you changed something the difference in hashed data decide if it should be send to next step.
  • then the queued assets are categorized, source code, source assets etc.
    *source code assets are imported then compiled in to .dll and the domain reloads
    And [InitializeOnLoad] is called
  • then the rest of the assets gets processed

In the forum post you use [InitalizeOnLoad] to bind to compilation which is weird, you sure its working? first is compilation then domain reload and then the InitializeOnLoad, so i dont know how you made it log anything.
So as long as your changes in script are not saved and unity doesnt refresh the assetDatabase it wont trigger the compilation anyway, so you can restore your script to what it was before editing save, reload and nothing happens.

merry tree
merry tree
#

I found a solution to the problem, but I need to figure out how to make it work now. The console/debug log, reports compilation exceptions. And it also removes those exceptions when they are resolved, even in the case here, where no compilation needed to occur.

I was worried this might be another internal validation, but I just tested a 3rd party asset to replace the console panel, and it also captures the removal of compilation exceptions, even when no recompiling occurred. This means it is absolutely possible to capture this state, without needing to force a recompile, and without internal access (though the debugger replacement might be using reflection to execute internals)

It means Unity is able to track these file changes/compilation exceptions for this edge case in a way I can use. I just need to discover how it is done.

scenic forge
pastel whale
#

logging which assembly failed is doable, but the compilation is trigged by the assetdatabase importer, and all of this stuff happens on native side and its not possibble to stop the process once it execute.

merry tree
pastel whale
#

if the compiled code inform you about error and you want to return it to its previous state (the .dll ), you should think of managing the AppDomain loaded assemblies and cache "good" assemblies (on disk) before compilation, so after compilation you can unload the wrong ones and load te cached good ones. The compilation wont occur if the script (source asset) is not different than the stored one, and the check if its different occurs on AssetsDatabase.Refresh()

#

you can get assemblies and their compilations messages from the compilation pipeline

merry tree
#

Sorry thats not the issue. I just need to know if the code I have on file is exactly what was used to build the current assemblies. I would prefer not to have to individually track all files for CS and potential CRC checks on each, and there seems to be a more efficient method I'll be able to use. Baking is a separate task that happens after validating the current saved code is already functional/built into the assembly.

pastel whale
#

if your file with code timestamp is after the the timestamp of .dll it means its not included, thats the simplest possibble check, other would require file tracking and/or storing metadata inside the script so you can check each .cs file

upbeat path
sage spindle
#

I want to generate a 3D island with water around it, anyone have advice on what I need to do this? I've seen some 2D generators but those use tilemaps. It doesn't have to use unity terrain or anything. The only rules I need are 1. Needs to be flat, or slighly elevated above the waterline 2. Needs to be an island 3. Needs to look "natural" around the edges with coves etc., maybe unity terrain is the best? Or I would need to create prefabs for edges and do a ton of math? If I have to use some noise function it needs to still be one landmass, not multiple islands

jaunty creek
#

Hi!

I am having some trouble understanding Input.gyro. I need the local x, y, and z rotations of the device as seen in the image (essentially the pitch, roll, and yaw). Input.gyro.attitude.eulerAngles.z works as long as the device is flat on the ground. If it is held pointing towards the horizon (like if I recorded a video), however, it no longer reads the local z-axis.

I found this post: https://web.archive.org/web/20180904151819/http://blog.heyworks.com/how-to-write-gyroscope-controller-with-unity3d/, but I can't see the example so I don't know how to calculate cameraBase and referenceRotation

Any help would be greatly appreciated. Thanks in advance!

echo coral
jaunty creek
# jaunty creek Hi! I am having some trouble understanding Input.gyro. I need the local x, y, ...

I found this post: https://discussions.unity.com/t/how-to-obtain-roll-tilt-angle-from-gyroscope/68115/2

"DeviceRotation.Get() is a wrapper for gyro input which adjusts the forward axis and takes different device orientations into account. Read more about it here" - But the link doesn't show anything about DeviceRotation.Get(), so

I guess my question is "How can I make a wrapper for gyro input which adjusts the forward axis and takes different device orientations into account?"

coral citrus
#

heya, looking for some input/guidance-

I have a custom terrain system (shown in pic) that's more or less a splatmap material with a bunch of other stuff stacked on top. I'm using these things I'm calling "painters" with some values (position, smoothing, color, etc.) that're being passed to a shader that renders all these details to a custom render texture, then another shader paints the terrain with those maps + determines where to place grass + etc.

something I'm a little confused on how to approach, though, is walking sound. grass is the default so that's easy, just play a grass step sound with animation events. but what about stone step sounds? my current idea is to bake sound indices into the alpha texture of the terrain map, but my problem with that is it seems like reading values back from the CRT so often would be super slow.

would it be better to try to just "guesstimate" where the player's stepping based on distance from the painters? or does this seem like an acceptable solution

misty glade
#

(or just grass if there's no painter within 3 steps)

coral citrus
#

that's kind of my thought as well, it's just a bit weird since the scale is based on percentages of each chunk rather than meters or flat sizing, but that still seems like the best solution

misty glade
#

(I'm assuming you have some non-shader representation of the "painter" so you don't have to access the shader to figure out what's closest?)

zealous summit
#

I'm adding en event to my game that will destroy parts of the level (a tilemap). To make it look good I'm removing only 2x2 tiles (blocks) from the tilemap. I was wondering is there a way to ensure that after removing blocks the tilemap will remain "blocky"? This means it should not contain any 1x1, 1x2, 2x1 tile combinations. I will leave a screen of an invalid tilemap after multiple removals.

    private bool TryGetBlock2x2(Tilemap source, Vector3Int tilePos, out Block2x2 block2X2)
    {
        block2X2 = null;

        Vector3Int[] positions = new Vector3Int[]
        {
            tilePos,
            new(tilePos.x + 1, tilePos.y, tilePos.z),
            new(tilePos.x, tilePos.y - 1, tilePos.z),
            new(tilePos.x + 1, tilePos.y - 1, tilePos.z)
        };

        foreach (var pos in positions)
            if (source.GetTile(pos) == null)
                return false;

        block2X2 = new Block2x2 { Positions = positions };
        return true;
    }

    private record Block2x2
    {
        public Vector3Int[] Positions { get; set; } = new Vector3Int[4];
    }
coral citrus
#

mhm, you can see an example of one here with the debug ball turned on

misty glade
coral citrus
#

so i just need to write something to determine the "true size" of them and then it'll be good

#

yepyep

misty glade
#

Unless it's jarring enough that you're playing the wrong sounds when you're clearly on grass (and playing like a hard stone footstep "click")

misty glade
zealous summit
#

yeah I also found out recently. It's quite cool for value variable types and has some built in functionality

#

but I just did a little research and it seems it can't handle neat declarations like below. The project runs on C# version 9 so in theory it should be fine. Might do more research later

public record Block2x2(Vector3Int[] Positions);

misty glade
#

Yeah - I mean, setting a language version or having visual studio accept what you're writing as valid C# is one thing, but having it work (with mono) is another.. I'm not 100% sure it will work as expected? I'm surprised it compiles just fine, though.. I would expect mono to complain about it

runic gazelle
# jaunty creek I found this post: https://discussions.unity.com/t/how-to-obtain-roll-tilt-angle...

That post seems like it has the answer already, just change the reference rotation to the axis angle you want, then run the function.
As for why Euler angles doesn't give you the answer you want, it's because Euler angles is actually 3 rotations, 1 along each axis. This can result in a rotation where the perceived angle is different from what you might expect. It should still be correct I believe

zealous summit
#

You shouldn’t use C# records in serialized types because Unity’s serialization system doesn’t support C# records.
Hmm, they serialize fine in editor in my project :)

#

Well it might not be as beneficial to use them in this case, I just though it was interesting

misty glade
#

I've setup a javascript plugin using the (very light) documentation here: https://docs.unity3d.com/Manual/web-interacting-browser-js.html

It works, I've got interop between unity and JS in the browser - but I don't understand it. What's mergeInto(LibraryManager.library, ...)? Is that a unity javascript library? Is there API documentation for it? Right now, it's just black magic to me and googling it just leads me back to this page.

#

Like, it works.. and I have no idea why. :p

devout hare
#

There isn't much more to it than what the documentation says. It's just the method for bundling custom functions into the game's Javascript code.

misty glade
#

k.. I'm assuming the mergeInto first parameter is always LibraryManager.library then? And I can just send it whatever I want in the 2nd param?

#

I couldn't seem to find any API doc for it.. but I mean, it works so maybe what do I care? 😛

#

abracadabra, javascript interop! waves wand

devout hare
#

Yes, it's always the same

misty glade
slow jay
#

Do you guys have any recommendations for profiling and optimizing a C# script that produces an effect and will be in the Unity Asset Store?

#

Maybe I should set some slightly vague platform requirements, because I can't choose what platforms or devices the users of the effect will make games for.

sly grove
misty glade
#

If it's $10 or $20 I'm buying stuff in a heartbeat - and if it's a few bucks and you can sell a few hundred of them, well, that's worth it for you, too, I imagine? A few days of work for something well done with an author who is responsive to bugs is worth it every time imho

#

Although maybe the market is small for something that's super niche so.. you know, balance the effort and the cost? People who are gonna buy it aren't idiots.. it's more about time savings rather than something they aren't capable of (for the most part, perhaps)

slow jay
misty glade
#

Ah, then probably just make it look sharp. I wouldn't imagine that FPS issues are gonna be what makes/breaks your item as a portfolio item

#

I imagine spending more time on the trailer will be "worth more" for your goals

dusty wigeon
bleak citrus
#

you could always toss it up on Itch or something similar

regal olive
#

Im trying to plan out a layering system for visual novels which uses a custom node system for sequencing things

#

its hard trying to think about how to manage the proper video, image, and sometimes animator layers

#

im thinking of using some sort of pooling system for each type of "rendering"

sly grove
dusty wigeon
#

I used 3.8 for Unity 2022.3

sly grove
#

I'm not married to an older version

wet sail
sly grove
wet sail
#

im pretty sure its an indexing problem but i cannot find out why

sly grove
#

What does "stops working" mean? What debugging steps have you taken and what were the results? What are you expecting to happen and what happens instead?

sly grove
wet sail
#

changing the code over and over and overthinking the logic. there'snt a debug stuff this isnt a game. its mesh generation.

sly grove
#

it has nothing to do with games

#

You can and should debug any code you write that isn't working.

wet sail
#

there's nothing to debug with mesh generation. its like debugging skinning. you fix your logic.

sly grove
#

It is code like any other

wet sail
#

im 100% not wrong. go on and debug a machine learning model

#

good luck

sly grove
#

Debugging techniques include:

  • Attaching a debugger and adding breakpoints to anal;yze the code at particular points
  • Adding log linies
  • Viusualizing the generated mesh with giszmos
sly grove
wet sail
#

this is like that but a bit less verbose

sly grove
#

I have written dozens of procedural mesh generators

#

and always debugged them

wet sail
#

ok. i don't know how

#

ok ?

sly grove
#

I just explained how

sly grove
#

Drawing labeled vertices and triangles with gizmos is an excellent way to visualize your generated mesh to see what's going wrong

#

Likewise, verifying that things are expected with simple Debug.Log lines is another valuable tool

wet sail
#

yea go on and teach me about debugging

#

ty

#

its fine

sly grove
#

I can sense you are upset, but debugging is the way to fix your code. Do you expect someone to just glance at this code and see something right or wrong in the logic off the cuff?

jovial bough
#

I'm trying to build my current version of my game - I have saved my project and restarded my computer - double check if anything is being imported but i have nothing - anyone might know what the problem actually is?

bright wind
#

I'm trying to render text using a TextMeshPro 3D object/mesh (non-canvas) into a RenderTexture using Graphics.DrawMeshNow(textmeshpro.mesh, matrix), and while it all works in editor and in dev builds, for some reason nothing shows up in full release builds. And I don't really have any idea what would cause this.

I'm using GL.LINE_STRIP drawing in the same RenderTexture and that shows up so it doesn't seem to be the RenderTexture. And if I push the source TextMeshPro into the camera view, it shows up with the text I'm trying to render so I don' think it's the material/shader itself. AFAICT, all the properties I'm using to place it (position, scale, etc) are all the same in the dev & release builds but for some reason it never seems to get rendered only in release builds.

No idea where else to start looking...

plush hare
#

Has anyone ever done custom wheel collider w/ slip friction?
I've got the slip ratio acceleration done fine. But what should be the behavior when the user completely lets off the gas pedal?

#

I was playing around in GTA and it looks like they just free wheel all of the wheels (so the wheel velocity matches the car forward velocity instead of vice versa) and apply a slight braking force for that. I would love if someone could help me verify that.

#

Not looking to do anything super realistic.

humble walrus
#

Does anyone here have a lot of experience with Animancer? I am genuinely about to lose my shit, trying to make it function the way I want.

When I run "Play", Animancer is seemingly purging ALL the events I have set up, and it warns me not to turn off the thing that does that, so how the hell am I actually meant to get the events set up with callbacks and delegates and all that stuff when the events are ceasing to exist?

https://hastebin.com/share/zitecuseye.csharp

#

Here is my code, for context.

#

I have an asset with a transition in it, I make a clone of a state derived from this, because I cannot make Animancer's unshared system work at all.

I have this cloned state, which has events on it. I want to assign methods to these events, so when the events on that state play, the associated methods play.

I play the state.

All the events on it disappear into the ether.

raven ruin
#

Besides, the entire piece of text is a dead give away it's gpt code, no wonder it doesn't work correctly

#

If you'd written it yourself, you'd likely have encountered your issue earlier on considering how important the vertexdistance property is to the entire system

left burrow
#

You should contact the makers of Animancer for support

humble walrus
#

The maker of Animancer is very verbose about his desire to not give "unneccecary" support, and can only be contacted through a few extremely slow methods.

#

additionally, IIRC, I am using the old version, which has been stated to no longer receive support now that the new extra-paid version is out

left burrow
#

well, you might get lucky and someone decides they want to make a thread and support a third party system. good luck

distant fable
#

Hello friends, I want to implement video call features into my game. I have come across Agora but it is no longer available on the Unity asset store. and I checked other solutions for this but most of them are deprecated. Do you guys know any solution for this?

raven ruin
zealous onyx
#

[Entities Netcode]
Hi need help about modifying colliders. I come across what seems to be a misprediction issue with the physics when changing the colliders height on runtime that launches the character in the air for a split second.

#

ive also already tried moving the collider modify logic on fixed step update (ghost) but the issue still persist

sly grove
#

suddenly the physics engine tries to depenetrate them, launching it up.

tired fog
#

I got a problem, Im trying to use Graphics.DrawMeshInstanced, and for optimization reasons i wanna use the render params property of camera, so that it only renders to the required camera. However, when doing so, the rendered graphics flicker in the editor

#

Does anyone know if there's any posible fix apart from not seting that value in the editor?

sly grove
#

Has anyone had any luck getting source generators work in Unity 6? I've been trying to follow this guide https://docs.unity3d.com/6000.0/Documentation/Manual/create-source-generator.html and pretty sure I followed all the steps, but it just doesn't seem to actually do anything.

My source generator code: https://hastebin.com/share/xijabopawe.csharp
Source generator CSProj file: https://hastebin.com/share/qatiwodepo.xml
Screenshot of the imported DLL included...

And finally trying to use the generated code I just have:

            var text = ExampleSourceGenerated.ExampleSourceGenerated.GetTestText();

Which results in:

Assets\Scripts\GameData\Commander.cs(46,24): error CS0103: The name 'ExampleSourceGenerated' does not exist in the current context
#

( I was trying things out which is why I had all platforms checked on the DLL but removing all the platforms results in the same)

thin mesa
sly grove
#

🤦

upbeat path
thin mesa
#

i would think that there would be an analyzer for the Generator attribute that would show an error for that though

#

if there's not, that's kind of silly. it should check if it implements one of the relevant interfaces

sly grove
# thin mesa your generator doesn't implement the ISourceGenerator interface

Yuuuuup that was it.

Sometimes you really do just need a fresh pair of eyes. Thank you.

I did think it was weird I was "implementing" methods like Execute and Initialize without an actual interface, but somehow didn't connect that to actually seeing if there was an interface I should have had. I chalked it up to a unity-like reflection scheme.

upbeat path
thin mesa
#

4.3.1 is the version bundled with unity 6

upbeat path
#

well 3.8 works with 6 as well

thin mesa
#

yes, but 4.3.1 has more features, like incremental source generators

sly grove
upbeat path
sly grove
#

I have just now gotten the basic example working 😆

#

No fancy features yet.

upbeat path
#

thats next then, have fun, DM me if you have problems

#

@thin mesa have you made one for Unity 6 ?

sly grove
#

I guess since we're here I can ask about my specific example. I'm basically trying to generate a new "companion class" for each of my data model classes that will be used for serialization. How would I get my source generator to effectively iterate over each class that derives from a specific parent class (in my case GameDataObject)?

#

Is that what something like SyntaxReceiver is for?

#

Happy to continue exploring docs to get there but since you're here...

upbeat path
#

yes, that is exactly the application for which I have written my source generator so I dont need to rely on reflection for serializing user classes

sly grove
upbeat path
#

So what I did is I made an Attribute which can be attached to a class
The Syntax Receiver searches for that Attribute and that gets passed to the Generator
The Generator generates a partial class with the same class name containing everything needed for the serializatiob

#

The MS docs are absolutely atrocious, theres a hell of a lot to find out about the Syntax Tree and the Symbol nodes work and hang together

#

and the worst thing is, you can't debug the dll it all working in

sly grove
#

I've seen people doing things like generating source that serves basically as a print function 😆

#

i.e. just outputting logs to a generated source file.

thin mesa
upbeat path
thin mesa
upbeat path
upbeat path
sly grove
#

Thanks for the examples you two, I'll be back if I run into trouble.

thin mesa
#

honestly makes things a lot easier since i could add methods for saving/loading directly to the class

upbeat path
#

well I add my own interface with it's required methods and it works like a charm and, nicely completely transparent.
Interestingly I fouund with testing rthat this method was 22% faster at runtime than using reflection with all it's boxing/unboxing

thin mesa
sly grove
thin mesa
#

that github link you posted here #archived-code-advanced message probably goes over it a bit better, but from my understanding it can reuse cached data and instead puts your data through different transformations to get what you want

upbeat path
#

It seems a shame, all that effort to write a nice save system and then you go and ruin it by using json

thin mesa
#

eh, it wasn't for anything super important and did what i needed. plus I wanted the save data to be easily accessible and edited for that project

undone coral
sly grove
#

@thin mesa how do I get it to only generate the code in Assembly-CSharp (or I guess some specific assembly)?

thin mesa
sly grove
#

If an analyzer is in a folder that contains an assembly definition, or a subfolder of such a folder, the analyzer only applies to the assembly generated from that assembly definition, and to any other assembly that references it.
Ahhh got it, ok thanks.

livid kraken
#

I’ve been meaning to augment our singleton implementation with source gen. The goal is to be able to decorate a class with a attribute and have a completely generate class handle calling the inits from all decorated classes. Would this incremental generator be the thing I use? I’ve never done any source gen.

sly grove
livid kraken
#

My understanding just from the names is that the regular one will run on every compilation generating the source file every time

sly grove
#

I think yes the incremental generator is essentially a performance optimization over a regular generator

livid kraken
#

I do love me some performance

scenic forge
#

Only recently found out that Unity supports incremental SGs now, haven't had time to play around with them but I guess my current SGs are also fast enough that I'm not in a rush to migrate.

hoary ore
#

Hey Guys 👋

Im currently using the Kinematic Character Controller as a base for my movement system.

Although im trying to implement Godot Logic into my movement system.

    public void UpdateInput(CharacterInput input)
    {
        _requestedRotation = input.Rotation;
        // take 2d input vector and create 3d movement vector on XZ plane
        _requestedMovement = new Vector3(input.Move.x, 0f, input.Move.y);
        // clamp the length to 1 to prevent moving faster diagonally with wasd
        _requestedMovement = Vector3.ClampMagnitude(_requestedMovement, 1f);
        // orient the input so its relative to the direction the player is facing
        _requestedMovement = input.Rotation * _requestedMovement;

        _requestedJump = _requestedJump || input.Jump;
    }
#
    public void UpdateVelocity(ref Vector3 currentVelocity, float deltaTime) 
    {
        // Grounded
        if (motor.GroundingStatus.IsStableOnGround)
        {
            // snap the requested movement in the direction to the angle of the surface
            // requested movement (basically just inputed movement)
            var groundedMovement = motor.GetDirectionTangentToSurface
            (
                direction: _requestedMovement,
                surfaceNormal: motor.GroundingStatus.GroundNormal
            ) * _requestedMovement.magnitude;

            // move along the ground in that direction
            currentVelocity = groundedMovement * walkSpeed;
        }

        // In Air
        else
        {
            // Gravity
            currentVelocity += motor.CharacterUp * gravity * deltaTime;
        }

        if (_requestedJump)
        {
            _requestedJump = false;

            // unstick player from ground
            motor.ForceUnground(time: 0f);

            // set minimum vertical speed to the jump speed.
            var currentVerticalSpeed = Vector3.Dot(currentVelocity, motor.CharacterUp);
            var targetVerticalSpeed = Mathf.Max(currentVerticalSpeed, jumpSpeed);

            // add the difference in current and target vertical speed to the character's velocity
            currentVelocity += motor.CharacterUp * (targetVerticalSpeed - currentVerticalSpeed);
        }
    }

Im attempting to use the following logic for unity but am having trouble with it.

the following is the godot code

#

any help would be much appreciated

#

this is what i attempted although it doesnt feel how it supposed to. like when you jump and rotate the camera the movement vector should sort of follow it in an arc (picture in source games) but instead it dosent

#
public void UpdateVelocity(ref Vector3 currentVelocity, float deltaTime)
{
    else
    {
        // In Air
        // Apply gravity
        currentVelocity += motor.CharacterUp * gravity * deltaTime;

        // Air Control Logic (Based on Godot code)
        // Normalize the requested movement direction (same as wishDir)
        Vector3 wishDir = _requestedMovement.normalized;

        // Camera-aligned movement direction (aligned with the camera's facing)
        Vector3 camAlignedWishDir = motor.CharacterUp.y != 0 
            ? Quaternion.Euler(0f, Camera.main.transform.eulerAngles.y, 0f) * wishDir 
            : wishDir; // Only adjust if the player is not moving strictly vertically (y=0)

        // Calculate current speed in the direction of movement
        float curSpeedInWishDir = Vector3.Dot(currentVelocity, wishDir);

        // Cap speed in the air 
        float airCap = 10f; // Maximum speed limit in the air
        float airMoveSpeed = 5f; // Speed factor while moving in air
        float cappedSpeed = Mathf.Min(airMoveSpeed * wishDir.magnitude, airCap);

        // Calculate how much to add to reach the desired speed
        float addSpeedTillCap = cappedSpeed - curSpeedInWishDir;

        if (addSpeedTillCap > 0)
        {
            // Add acceleration until the speed cap
            float accelSpeed = airAccel * airMoveSpeed * deltaTime; // airAccel is how quickly you reach airMoveSpeed
            accelSpeed = Mathf.Min(accelSpeed, addSpeedTillCap); // Prevent overshooting the cap
            currentVelocity += accelSpeed * camAlignedWishDir;
        }
    }

}
midnight violet
thorn flintBOT
hoary ore
midnight violet
hoary ore
#

lemme record a video, easier to show then tell, ty for helping

livid kraken
#

The entire repo is interesting but this code writer seems to come from MS themselves and seems generic enough for any code gen use. Wonder why it does not use string builder….maybe it’s older hah

scenic forge
#

There are lots of different approaching to actually generating the code, you can use Roslyn API to construct syntax tree directly, use interpolated strings, have your own simple wrappers like the one linked, or use stuffs like scriban.

#

The general wisdom seems to be "just use interpolated strings and call it a day," people have gone down the Roslyn API route and ended up a monster that no one else understands.

upbeat path
livid kraken
#

Good to know

jolly wraith
#

Hello,

I coded a custom EditorWindow for a GraphView. It's working well (cut/copy/delete/paste), but I can not find a way to rename/edit the title of node.

The workaround I use so far is to add an entry rename in the BuildContextualMenu or the GraphView, then if right click on node -> rename, a window popup (new Editor window with 1 field and a button ) , and it recreates the node ..

it seems a bit heavy, Im not sure how to just have the TextField change/switch to edit.

Thanks

hoary ore
# midnight violet Can you explain a bit more, what "It doesnt" mean in your case?

https://drive.google.com/file/d/1LsZV5T1-8imrObE719C-LlxtLqtkOf-t/view?usp=sharing
basically how it arcs and like sort of follows the camera in a way. or do you think i just needa tweak the settings
and heres the godot movement code ive been referencing
https://www.youtube.com/watch?v=ZJr2qUrzEqg&t=2183s

The first video of a series where we will build an FPS game. This video shows how to implement source engine like movement mechanics.
STARTER PROJECT: https://github.com/majikayogames/SimpleFPSController/files/15273600/StarterProject.zip

Full Playlist: https://www.youtube.com/playlist?list=PLbuK0gG93AsHID1DDD1nt4YHcdOmJvWW1
GitHub Repo: https:/...

▶ Play video
sly grove
#

Anyone else having this problem with Roslyn Source Generators in Unity 6? I get an error in console whenever Unity reimports/recompiles:

Asset path could not be found for script compilation file 'DDGameDataSourceGenerator/DDGameDataSourceGenerator.GameDataObjectGenerator/GameDataInterfaces.cs'

But my code generator and everything else works just fine. It's just an annoying clear-able error. Found a similar discussion thread here but no answers:

https://discussions.unity.com/t/roslyn-incremental-generator-unity-throws-exception-for-source-file-generated-in-registerpostinitializationoutput/1529088

sly grove
upbeat path
#

how ironic @sly grove needing to be told how to post !code

thorn flintBOT
sly grove
#

lmfao

#

Ironically yes I rarely share my own code and am apparently bad at it.

upbeat path
#

rofl

sly grove
drifting solstice
#

smh using java in unity

sly grove
#

Is it because I did context.AddSource("GameDataInterfaces", Interfaces); instead of context.AddSource("GameDataInterfaces.g.cs", Interfaces); 🤔

upbeat path
sly grove
#

yes

upbeat path
#

you need the .cs so it's picked up by the Unity .csproj generator

upbeat path
#

bah, humbug, Unity docs, who would ever recommend them? Oh, yes, us, all the time

#

mind you, when you get to source generation (and this is code advanced) you could kind of expect that a C# source file would have a .cs extension

sly grove
# upbeat path that will do it, yes

Sad to say, that did not fix it.

My new error:

Asset path could not be found for script compilation file 'DDGameDataSourceGenerator/DDGameDataSourceGenerator.GameDataObjectGenerator/GameDataInterfaces.g.cs'

upbeat path
#

what folder is your dll in?

sly grove
#

<project folder>/Assets/Scripts/SourceGenerators

#

Scripts has an asmdef in it

upbeat path
#

try putting it in a Plugins folder

#

ah, asmdefs, not done source gen with them

#

I'm guessing that the generated code is not being added to the asmdef .csproj file

sly grove
#

plugins didn't help - I'll take a look at the csproj

upbeat path
#

this is something I was wondering, I make partial classes and they only work when they are all in the same assembly which means, generally, that the source generator must be adding the generated code to the Assembly-CSharp assembly

sage radish
#

It's probably just some part of the compilation process that doesn't consider the possibility of source generated files being outside of Assets with no .meta file.

sly grove
#

Rider autocomplete was happily suggesting 25 different copies of my generated class

upbeat path
sly grove
#

Indeed my GameAssembly.csproj file does not include the generated files 🤔

scenic forge
#

There are also two other approaches I've seen rather than using assembly definition to scope the SG.
First is probably the proper way, if for example you are scanning for classes with a certain member in order to generate some companion class for it, and the companion class requires some kind of interface, rather than unconditionally generating that interface which results in it existing everywhere, only generate on demand. If there's nothing that requires generating a companion class, then don't generate the interface.
Second is a quick and dirty solution, just check context.Compilation.AssemblyName == "Assembly-CSharp" and skip otherwise.

upbeat path
# sly grove Indeed my GameAssembly.csproj file does not include the generated files 🤔

that's seems ok, mine doesn't either. Does your csproj contain something like this

<ItemGroup>
    <Analyzer Include="C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\Microsoft\Visual Studio Tools for Unity\Analyzers\Microsoft.Unity.Analyzers.dll" />
    <Analyzer Include="E:\Production\SaveForUnity\SaveDevelopment6000\Assets\Plugins\SourceGen.dll" />
    <Analyzer Include="C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll" />
    <Analyzer Include="C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.Properties.SourceGenerator.dll" />
    <Analyzer Include="C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.UIToolkit.SourceGenerator.dll" />
  </ItemGroup>
sly grove
# upbeat path that's seems ok, mine doesn't either. Does your csproj contain something like th...

something like that yeah

<ItemGroup>
  <Analyzer Include="C:\Users\sadnessmonday\delta-draconis\Assets\Packages\MessagePackAnalyzer.3.1.0\analyzers\roslyn4.3\cs\MessagePack.SourceGenerator.dll" />
  <Analyzer Include="C:\Users\sadnessmonday\delta-draconis\Assets\Packages\MessagePackAnalyzer.3.1.0\analyzers\roslyn4.3\cs\MessagePack.Analyzers.CodeFixes.dll" />
  <Analyzer Include="C:\Program Files\Unity\Hub\Editor\6000.0.32f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll" />
  <Analyzer Include="C:\Program Files\Unity\Hub\Editor\6000.0.32f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.Properties.SourceGenerator.dll" />
  <Analyzer Include="C:\Program Files\Unity\Hub\Editor\6000.0.32f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.UIToolkit.SourceGenerator.dll" />
  <Analyzer Include="C:\Users\sadnessmonday\delta-draconis\Assets\Scripts\SourceGenerators\DDGameDataSourceGenerator.dll" />
</ItemGroup>```
#

I do wonder now if the fact that I started building the code generator DLL from Rider instead of VS was a mistake >_>

#

I was curious if I could, and I started doing so, and it seemed to work

#

it DOES work

#

but maybe it doesn't work perfectly 🤔

sly grove
upbeat path
#

I'm wondering is this an artifact of 4.3 instead of the 3.8 I'm using

sly grove
#

that is maybe also possible??

#

I'll try a few things...

upbeat path
#

It could be a rider thing, I notice mine has a reference to VS 2019 (which is my VS preference in Unity) even though the dll was built with VS 2022

sly grove
#

Building the DLL in VS didn't fix it

upbeat path
sly grove
#

nor did it change anything in the csproj file

#

Weirdly I don't have this <Analyzer Include="C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\Microsoft\Visual Studio Tools for Unity\Analyzers\Microsoft.Unity.Analyzers.dll" /> at all

upbeat path
#

I'm going to try generating a partial class from an assembly not Assembly-CSharp, wait one

#

@sly grove It has, indeed, failed to generate a partial class that is not in Assembly-CSharp

sly grove
#

I think I just did something that actually affected my issue... though I'm now confused because something seemingly entirely unrelated broke at the same time.

I moved the generation of those two "static" files out of PostInit and directly into Execute and now I don't see that error from above.

#

At the same time, some of the logic in my source generator seems to have broken, in a purely behavioral way, and not in those particular files I just messed with. 🤔
Of course I was not scientific about this and changed too many variables at once probably.

upbeat path
#

note. that is why I made the Trace method in the generator so I could test if generation actually took place

#

tbf, I've only been messing with this stuff for a week so I could easily have missed something

#

maybe @thin mesa can shed some light?

upbeat path
scenic forge
#

I don't use VS, but IIRC if you go to solution explorer and locate your SG, you can expand it and see all the generated sources in there.

upbeat path
#

Bit of a give-away, not in the csproj file

upbeat path
scenic forge
#

Those generated sources are not nested under the project, they are nested under the SG.

#

Fairly certain that's a thing, but I could be remembering wrong since I last used VS was quite awhile ago.

upbeat path
#

this is VS 2019 btw

#

that is cool

scenic forge
#

Yeah, makes debugging what SG actually generates quite a lot easier.

turbid tinsel
#

I'm experimenting with some "proper" code architecture for the first time, and I've been thinking. I have something similar to an EventBus, managers, and game/ui elements. Current flow is that UI communicates to managers using the EventBus, but communication FROM the managers to the game/ui elements is a mix of events (located on said managers) and the EventBus.
I have a neat way of passing data through my EventBus, though... should I minimise the usage of events located on the managers, in favour of the EventBus? Or is that a futile effort?
I am already using DI for inserting the managers into my game/ui elements so that's not an issue, but I'm thinking if I'll be able to achieve complete manager/ui separation so that they can be in separate assemblies, that'd be cool.

compact ingot
#

that said, keep your ui and input code as far away from your systems/logic as possible turns out to be a good idea in any case.

turbid tinsel
#

And currently we're discussing how exactly the project should be set up in regards to what uses the event bus, what uses event listeners etc etc

compact ingot
#

an event bus for example is typically only nice on one side (it promises a unification of all messages and hooks into that) and will mess up your remaing project terribly (by making it impossible to coordinate the messages in an understandable way)

turbid tinsel
#

I do understand the need for an eventbus, but I'm asking specifically for other's experiences in this. I want to know how far to push it, and if splitting the code enough to keep managers and ui in separate assemblies, is feasible

compact ingot
#

so typically what happens is: you have one system that benefits greatly from an event bus, and you should use one there, but you should not make that one reason why every other system also has to use it. I.e. constrain the scope of your architectural decisions.

turbid tinsel
#

I WANT to try it, but I've never done it on this scale, so I'm asking

potent shoal
#

Octia, take that event bus and run with it.

#

If you lose a tire, just change it.

#

I've only had the alternator go out once, and that too can be fixed.

compact ingot
turbid tinsel
compact ingot
turbid tinsel
compact ingot
#

how many people in the team?

turbid tinsel
turbid tinsel
compact ingot
#

alright, so my opinion is, all this archiecture will only hold you back in a 3-person team but will be required in a larger team live service, not the least because its the expected architecture in live service mobile games

#

for some reason mobile live service has decided to use DI containers, reactive patterns and the inevitable event bus to tie it all together

#

together they make sense, but only if your team actually needs it.

potent shoal
#

Octia, a well designed event bus is programming freedom. Seriously.

you're taking damage, you dispatch the damage event, and suddenly anything anywhere can catch it. Without the event bus, suddenly, you're in the Player settings menu, wondering how to capture player damage for some reason, and then create an awkward forced tunnel to that data

#

event bus = freedom

#

no event bus = no sleep

compact ingot
turbid tinsel
turbid tinsel
#

I just wonder how far to take it when I'm running with it

turbid tinsel
potent shoal
#

@compact ingotI think of an event bus like the perfect singleton.
It's essentially an event system that anything can listen on, and anything can push to. It's useful for everything, and useless for nothing. It doesn't take much to build it, and it doesn't take much to use it. It's complex to not use it, because it requires spaghetti.

#

I have been building a MMO for 9 years. In my game, we use an event bus, however it's a much more complex event bus than most people can wrap their heads around.

We actually run our UI out of ASP.NET Blazor and this uses a networked event bus between game servers to maintain a stateless architecture. A little different, but even without my scale, event busses are necessary.

turbid tinsel
compact ingot
turbid tinsel
compact ingot
#

but i'm curious

#

i've only ever seen event busses turn into to turds, so if someone knows how to make them work, what to look out for, i need to know that !

potent shoal
#

I see.

turbid tinsel
#

my current plan for the project lmao

#

procedures are our name for events*

potent shoal
#

I like to keep event busses simple.
There is a container class called "Event", which contains it's event type, and also generic methods to get and set it's content. It can also set multiple arguments to the event object if necessary.

That provides a lot of flexibility to pushing out and getting data without too much constraint. Anything can go through it.

#

Cleanup can all be internalized as well.

scenic forge
#

I was just about to ask how do you ensure type safety. I guess the answer is you don't?

potent shoal
#

this is an example of how we manage our networked event bus. We do have type safety.

#

The example I provided was very very simple.

turbid tinsel
# potent shoal I like to keep event busses simple. There is a container class called "Event", w...

we're doing it differently - each event is its own struct deriving from a base class, with custom data, although your approach is rather cool too. We have a manager for it, that calls the pre and post apply events, and in between it runs the apply function on said struct, which does whatever processing the event wants to do. It's usually kept pretty simple, as to not depend on anything. Anything can register with the manager, to listen for events of specific type

scenic forge
#

I don't see how that has any type safety, what stops code from calling GetContent<NotTheCorrectTypeForThisMessage>()?

turbid tinsel
#

well, we have a wrapper for an event group, you call that, but you can only recieve Events

turbid tinsel
#

I mean not work properly

potent shoal
#

@scenic forge interesting. our type safety isn't set at event level, but at subscription level.

scenic forge
#

Explodes are runtime sure, but that's not compile time type safety.

turbid tinsel
#

Velcer said it doesn't have type safety but their full system does

potent shoal
#

So the method recieiving this event would already be self aware.

compact ingot
#

are we talking about event bus for network distributed services or about a model for implementing process-internal logic?

turbid tinsel
potent shoal
#

@turbid tinselI believe in a little more freedom.
If you set yourself up to require every message to need that base class, then every message needs that base class. Long term, you might run into some problems. I see it as unnecessary additional overhead.

When I subscribe to my bus, I am informing the bus what event type I am listening for, so my receiving method is already aware and can do generic processing of my "EventMessage" class.

#

In this way, anything can go through EventMessage, anything and everything.

turbid tinsel
#

a pretty empty one, it just has a single apply function in case you want to do some processing

scenic forge
turbid tinsel
sage radish
turbid tinsel
#

I do it by defining classes inheriting from a common interface, each class being an event type

sage radish
#

I've used an event bus like this for a shipped product, in a 3-4 man dev team. No complaints, has solved a lot of problems.

turbid tinsel
potent shoal
#

I really like that @sage radish

#

Very clean, very simple.

scenic forge
potent shoal
#

@scenic forgeoh, string key? trust my I do way worse

turbid tinsel
#

XD

potent shoal
#

for example

public partial class MessageTypes
{
    public class InputFeedback 
    {
        public static uint VERTICAL = GetId();
        public static uint HORIZONTAL = GetId();
    }

    public class Input
    {
        public static uint VERTICAL = GetId();
        public static uint HORIZONTAL = GetId();
    }

    public class Ship
    {

        public static uint MAX_SPEED = GetId();
        public static uint AGILITY = GetId();

        public class Visual 
        {
            public static uint HULL_ASSET = GetId();
            public static uint ENGINE_ASSET = GetId();
            public static uint WING_ASSET = GetId();
        }

    }

    public class Cluster
    {
        public static uint GameServerInitialized = GetId();
        public static uint RoomInfoPackage = GetId();
    }
}

public partial class MessageTypes
{
    private static Dictionary<uint, string> _numberToStringMap = new Dictionary<uint, string>();

    public static uint GetId([CallerMemberName] string fieldName = "", [CallerLineNumber] int numId = 0)
    {
        string fullName = $"{fieldName}.{numId}";

        if (!_numberToStringMap.ContainsKey((uint)numId))
        {
            _numberToStringMap[(uint)numId] = fullName;
        }


        return (uint)numId;
    }

    public static string GetOriginalString(uint uniqueNumber)
    {
        if (_numberToStringMap.TryGetValue(uniqueNumber, out string originalString))
        {
            return originalString;
        }
        return $"{uniqueNumber}"; 
    }
}```
#

although this is a snippet for some netcode, it's how I handle a lot of types.

#

I hate strings because you can lose them.

#

I hate enums, because they get too big.

#

I use this approach because I can manage everything into their own nested classes.

#

CallerMemberName and CallerLineNumber are my favorite attributes in c#

#

and I do abuse them whenever I can find a possible reason to

turbid tinsel
turbid tinsel
compact ingot
potent shoal
#

Everywhere in my codebase.

sage radish
#

It's an interesting use of those attributes, but I don't know how I feel about using the line number as the ID. I assumed you were combining the member name with it to get something more unique, but it looks like this will silently fail if you define message types in a separate file with overlapping line numbers.

potent shoal
turbid tinsel
#

wait what, I really need to look up what that attribute does

potent shoal
#

You're correct, it does have limitations.

#

@turbid tinselLineMember returns the line, caller name returns the method name

potent shoal
#

yep

turbid tinsel
#

god this is cursed

potent shoal
#

yep

turbid tinsel
#

😭

potent shoal
#

I love these so much, that I wrote an entire asynchronous data architecture depending on them.

for example, this class can be created anywhere in my code base with "ItemObject.Create("ItemId")", and get an asyncronous model that can automatically load data on demand, without loading the entire model.

public class ItemObject : AsyncDocument<ItemObject>
{
    public override string GetCollectionName()
    {
        return "item";
    }

    public AsyncProperty<string> Description => new AsyncProperty<string>(Key);
    public AsyncProperty<List<string>> Lore => new AsyncProperty<List<string>>(Key);
    public AsyncProperty<string> Base64Icon => new AsyncProperty<string>(Key);

    public AsyncProperty<AttributeSet> Attributes => new AsyncProperty<AttributeSet>(Key);

    public AsyncProperty<string> AssetId => new AsyncProperty<string>(Key);

    public AsyncUniqueIndexedProperty<string> DisplayName => new AsyncUniqueIndexedProperty<string>(Key, IndexType.Text);

    public AsyncIndexedProperty<string> Category => new AsyncIndexedProperty<string>(Key, IndexType.Tag);


    public AsyncIndexedProperty<bool> IsEquippable => new AsyncIndexedProperty<bool>(Key);

    public AsyncIndexedProperty<EquipmentType> EquipmentType => new AsyncIndexedProperty<EquipmentType>(Key);
}```
#

Description.GetAsync, for example, returns a live, fresh data for description.

#

And I even managed to internally index my data models 😄

turbid tinsel
potent shoal
#

no, just caller member name

#
public AsyncProperty(
    string documentKey,
    T defaultValue = default,
    Func<T, Task<T>> getProcessingTask = null,
    Func<T, Task<T>> setProcessingTask = null, 
    [System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
{
    _documentKey = documentKey;
    _defaultValue = defaultValue;
    _propertyName = propertyName;
    _getProcessingTask = getProcessingTask;
    _setProcessingTask = setProcessingTask;     
}```
turbid tinsel
#

Caller member name is just a string but worse

#

caller line number is the most cursed thing I've seen in a while

potent shoal
#

it's very useful

turbid tinsel
#

I bet lmao

potent shoal
#

you just have to get passed your internal bias

#

it's like love

#

just at second sight

turbid tinsel
#

the internal bias of maybe modifying my files someday?? 😭

potent shoal
#

everything updates.

#

you change it, everything that depends on it changes too

#

I doubt you would hardcode, or save that line member somewhere

#

it's jsust a message type

turbid tinsel
#

it's a partial class though, it can overlap, can it not?

#

someone mentioned that here already

potent shoal
#

partial class isn't necessary. I only did that because I wanted to seperate my logic from my types.

turbid tinsel
#

yeah but you DO HAVE a partial class in your code there

#

with something that I'd assume has a lot of line conflicts

#

line number conflicts

#

I cannot believe I'm typing this out loud even

potent shoal
#

no, there's no conflicts. Both classes are in the same file.

#

I just wanted a clean way to seperate my logic for handling ids.

turbid tinsel
#

Ah, a big benefit I saw to using a partial class for this is using it across multiple files

potent shoal
#

I could just use a manager class

#

but effort

turbid tinsel
#

and also it feels like it'd grow a bit big

#

eventually

#

wouldn't it

sage radish
#

The usage of CallerMemberName in AsyncProperty is fine. It's a bit invisible, so new team members will have to be introduced to it to ensure they don't accidentally use it wrong, like creating them in a constructor or somewhere else.

potent shoal
sage radish
#

But the use of line number for message types is too limiting and dangerous, in my opinion.

turbid tinsel
#

CallerMemberName can actually be pretty useful for some things, I really expected something like that to need a bunch of really annoying reflection, but I guess not

potent shoal
#

You can also combine class name

turbid tinsel
sage radish
potent shoal
#

@turbid tinselfor more safety, you can use stack trace to ensure that your message types are original.

turbid tinsel
potent shoal
#

It's not, but it is safe.

#

And the overhead isn't that bad.

sage radish
#

I prefer using types as identifiers whenever I can. Even empty structs passed around as Type. The type system ensures there are never conflicts. It does sometimes get verbose, especially if you have a separate file for each type, which I usually do, but the safety is worth it.

mental escarp
#

Hey, before I start, this is most likely not an advanced question, I am asking here because the q is a bit longer and this seems to be th least active cheat so yeah.
I've been struggling with getting rid of the framedrop caused by executing a shell script.
I know that this sounds odd for a game, but it's not exactly a game, it's a visualizer, and I'd like to be able to display system stats and run shell commands from the game itself.
I am currently starting a new thread to execute the shell command, as can be seen in this script.
This actually works really well if I am not executing a shell command, but getting current time or fps instead, as can be seen in these functions.
However, if I try to run a shell command with this function, the fps drops to ~25 from 60 or so.
This is obviously a huge issue since I need to execute these commands anywhere from once every 60 minutes to once every .1 seconds.
Even if it was once every 10 seconds, it's still insanely annoying because you can definitely tell that there was an fps drop.
I tried p much everything that comes to my mind so I'd really appreciate somebody more experienced giving me their input on this.
Please @ me when replying and thanks in advance!

echo coral
#

You have 0.016 ms per "update" but if you introduce a 500ms + pause then ofc you will get problems.

mental escarp
echo coral
# mental escarp bothered going through code I attached?

I checked each link but i am not going to look at the usage of each function.
As soon as i saw process.WaitForExit(); I concluded this is the most likelly cause.

Are you executing the process for a shell cmd on the main thread then (ExecuteShellCommand())?

mental escarp
#

afaik that should start a new thread for that process and the second line should basically check if task is complete each frame

echo coral
mental escarp
echo coral
mental escarp
#

yep, that's what I'm trying to do now, I also increased max fps from 60 to 240 to make it more extreme ig, we'll see

#

but yeah, just a quick glance at this prob tells you that it's pretty bad :/

#

yup, 0 clue what this is, p sure it's related to the vfx graph or something

brave cairn
mental escarp
#

because if I disable them, and let me make sure, it doesn't drop anymore

brave cairn
#

Obviously should behave much better

scenic forge
#

(This is why you always profile first and understand what the issue is, rather than guessing and chasing a ghost)

#

Are you using a giant or dynamic font size?

mental escarp
scenic forge
#

No, that should be fine.

mental escarp
#

Both capped to 120fps to avoid gpu overuse

  1. With ui
  2. Without ui
sly grove
#

It's so beautiful 🥹 thanks for your help with the source generators @thin mesa and @upbeat path

mental escarp
misty glade
sly grove
misty glade
#

I also echo what steve told you (hours ago) that I wasn't able to get partial classes working properly in different asmdefs

#

I tried (and failed) for a while to cleave my logic singletons apart into a sort of... roll my own DI framework (some testing stuff that wouldn't ever be in production builds) and it just kinda failed miserably

#

as a result I have a lot of this chaff which I'm embarassed about

#

Anyway, sorry for the OT - glad you got your SG working. Out of curiosity, whatcha using it for? I noted the messagepack keys - are you doing something for generating the messagepack ~~annotations ~~ attributes in DTO/POCOs?

sly grove
misty glade
#

I'd be interested in what you roll up. I've done it.. 3? different ways in the past couple years and I hate all of them

sly grove
#

Basically generating flat DTO types corresponding to my game model objects to be serialized with MessagePack

misty glade
#

Not gonna lie.. one of them involved .ini format files

#

(that may have been the worst)

misty glade
sly grove
#

I'm trying to write the deserializer now. Basically - trying to preserve reference semantics in a nice way in any serialization scheme sucks and I'm trying out a technique I used professionally years ago for a non game project to see how it works

#

But yeah in the past I've done approaches like this without code generation and there's sooo much boilerplate to write

#

and "things you need to remember to do" when adding new types, fields, etc to the model

misty glade
sly grove
#

I'm seeing if codegen can alleviate some of that tedium and error-proneness

misty glade
#

I still haven't "solved" (to a satisfactory way) the data migration headache when a product and save files are already live

#

Oh god.. this is embarassing.. DataMigrationTool.cs from 2019...

#

Looks like I had a method for migrating every data version .. which I'd call (repeatedly) based on what version of the player file they were on

sly grove
#

That's actually lovely and I can't think of a much better way to do it 😆

misty glade
#

The funny thing is.. I look at this and my jaw drops.. but ... I don't have an obviously better solution

#

I feel like a more robust approach would just be to have default values for fields, but maybe I'm just failing to remember the downsides of changing data.. FWIW this was for an "player files on the server" MMORPG .. and while there were never any data "crashes", I recall spending tons of time fiddling and thinking about data and migrations

#

especially all the networking messages - like if a player connected on an old version or sent malicious/malformed packets .. how to tell them

midnight violet
#

This looks like the outcome of a not very well thought through class setup OR its just that complex and you need it 😄

bleak citrus
misty glade
#

Perhaps, but "not very well thought out" is also a negative way of saying "things change over time".. especially so in video games.. I think after two decades of being a programmer / product manager.. it's frankly impossible to have a game's scope be set in stone before writing some code

bleak citrus
#

I had an array of migration functions that took you from X to X+1

misty glade
#

Especially for an MMORPG

bleak citrus
#

and I'd just run those on your save file until the version number matched the length of the array

#

Having absolutely zero static typing made this pretty convenient to write

#

(the 0 -> 1 migration just displayed a "sorry" message)

misty glade
#

Like I said.. I don't know that I'm super happy with my solution, since it was really fragile and lot of work.. but.. it worked? whenever there was a data change from version to version, I'd write the corresponding migration function and add it to the list of "things to run on a player file" if they connected with a certain version

#

or alternatively, run it against the entire database to upgrade all the players in the database at once

bleak citrus
#

That's also how I would handle it. It would be nice to have a way to not have to hand-write anything, I guess

#

in my ideal world, I'd just leave all of those old serialized data types untouched

#

PlayerSave1 would never ever change after shipping version 1 of the save data

midnight violet
bleak citrus
#

so if you deserialized a PlayerSave1, you'd know you need to run the function that turns it into a PlayerSave2

#

I guess you could use aliases everywhere to avoid having to reference a specific version number

#

Everything in your game would just use PlayerSave

#

which would be aliased to, say, PlayerSave6

#

Hey, I kind of like this idea...

misty glade
midnight violet
#

Also a "dictionary" telling the game version to use which save file version might help. SO you can update frmo server side but keep running local versions

bleak citrus
#

only the serializer would need to care about specific versions

#

you wouldn't let that stuff "leak" anywhere else

misty glade
#

here's a snap of the player model "parent" object

#

it has nested child objects.. plus it has it's own set of private fields that don't get sent to the users (because they're untrusted or whatever)

bleak citrus
#

my heart briefly sunk when I spotted "99+ references"

but that IS the player's GUID 😉

misty glade
#

so all of the hydration methods have to scrub the files coming in and going out

bleak citrus
#

not the worst thing to be heavily-used

misty glade
#

so there's an internal id and an external id :p

#

(and then the database required it's own naming for a guid)

bleak citrus
#

I have at least two kinds of GUID in my project, yes

#

I'm so happy

misty glade
#

i went to some sort of nano ids for one of my games that required some humans to touch them

#

guids are fine for "non sequential but almost certainly unique ids" but terrible for humans

#

I've played games before where i've needed to type or otherwise "use" a guid and I was so annoyed

bleak citrus
#

yeah

#

i am considering adding redundancy to my settings file format

#

because, whilst this is great for me, it might be a nuisance if you wind up needing to edit it by hand...

#

(well, hopefully, you never do)

scenic forge
bleak citrus
#

yeah, I got into TS later

#

it was wild

#

types!

bleak citrus
#

or go to a binary format

echo coral
#

Where I work we use protobuf for our configuration and player data.

bleak citrus
#

I've always known about protobuf, but I've never actually poked at it

echo coral
#

We like it as we also use it for client to server communication as it can be compiled for c# and scala but we have a custom modified version of the compiler.

scenic forge
#

It's basically just yet another de/serialization format, with the charm point that schema is standalone and can then be compiled to multiple languages.

misty glade
#

I like messagepack for it but.. only because the protobuf documentation seemed inscrutible at a glance

#

(I also like the dude who made messagepack)

echo coral
#

I've used it a lot so im used to it and its limitations. Its quite easy to go to/from bytes for it so i like that too.

#

Its also very efficient once serialized and quite tolerable to deserializing differing versions (as long as you use optional and not required and do not re use ids if no longer used).

half shoal
#

Does anyone know the maximum number of Culling Groups in Unity?
I’m implementing a custom LOD Group system using Culling Groups for an open-world game. Since objects are loaded and unloaded in chunks, it’s difficult to manage them using a single array of Culling Groups.
Instead, I’m creating one Culling Group per chunk. However, when the number of chunks exceeds a certain limit, this approach seems to stop working correctly.

I suspect there might be a limitation on the maximum number of Culling Groups allowed by the engine.
Does anyone have clear information on this limitation, or has anyone resolved a similar issue using an alternative solution?

eager reef
#

Hey all, is it possible to create a custom collider type? Mesh collider isn't what I'm looking for.

Use case: i'm using a data structure called a sparse voxel octree to store data related to blocks in my world, and I'm generating unity meshes from this information. I can very efficiently determine collisions using this data structure, so I'd like some way to define if a collision has occured or not using a custom method which uses the SVO

#

This is the API I need exposed

sly grove
#

You could look into UNity Physics instead (confusingly not the same as the built in physics) which I believe gives more flexibility...

#

but it's part of DOTS

eager reef
#

good thing im working in ecs

#

looks like no

sly grove
#

yeah looking like still no... despite the confusingly titled "custom physics shapes" heading

#

you're probably looking at doing custom physics

eager reef
#

so annoying, how is there no way to define if a collisions occured or not?

stiff wasp
#

BetterPhysics from the asset store 😄

eager reef
#

that has what im looking for?

stiff wasp
#

Not sure, was helping PraetorBlue with his asset lol

#

I announce my departure here

sly grove
#

I am the author of that asset and it certainly does NOT have what you are looking for lol

eager reef
#

dang, right from the source lol

eager reef
#

looks like modification point 2 is the golden ticket

#

talk about luckyy

#

you dont get these access points with unity physx

winged holly
#

Scene manager not working

#

Do I need to make any settings in Unity 6?