#archived-code-advanced
1 messages · Page 117 of 1
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
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
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:
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
pretty much yes
but only in some cases
in a three dimension space there are 24 cases possible
This is tricky because you can't, given only an up vector, consistently choose a forward direction
i thought that too, but then why does it work between -y +y and +x?
I bet it's just right 50% of the time and wrong 50% of the time
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
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
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
pretty much yes, the whole movement script is about 1000 lines, so it's hard to narrow it down, but yes
uhhh this code is probably overcomplicated - i would just be doing vector math and projection based on the surfaces you see - with some raycasts
Depending on exactly how you picked the forward and up directions, the meaning of that extra Y rotation will vary
And like - this stuff is spooky
im not really a beginner but i'm no expert too, so this is what i was able to come up with
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"
why's that?
comparing for exact equality with vectors is weird
It's kind of okay in this case because you only have six possible vectors
Because for one it's way too specific, and for two, direct comparison of vectors like this is unreliable
It does also smell like a "hack", yes
a special case where you just give up and use a fixed value
yeah i did that because there's pretty much no way the player will have a gravity different than that
A better system would be able to handle any angled surface whatsoever which would make this kind of explicity comparison completely infeasible
i only use 6 fixed gravities
I think you need to include your original basis vectors when figuring out the new basis vectors
sounds out of my league tho :(
you need some extra context here
sure and that means you need like... 6 if statements? or something?
This can all be condensed
Vector math is learnable!
you're not just picking a new "forward" and "up" direction in a vacuum
it's not really that bad!
you're trying to pick directions that are consistent with your original "forward" and "up" directions
I learned a whole lot from writing shaders
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:
What direction is even the "correct" direction to be facing, anyway?
that's the problem
sure that doesn't really change the question in any way. - but you can very easily just take the up vector of the pad and use that as the new gravity (or the opposite of it at least)
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
i thought about that, but what if the pad isn't rotated perfectly? this is a level editor, i have no guarantee what a user can do
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
Isn't that fine?
You want to walk on the pad
no matter what its orientation is
if not - then you'll be clippign through it?
I wonder if you can use Quaternion.FromToRotation here
Which sounds worse
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
where would this go in my code?
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);```
since you seem pretty expert with this thing, could you explain me why the +x rotation works fine in more technical terms? @bleak citrus 's explanation was good, but i can't seem to translate it to technical terms, do you have a more in depth explanation on that?
im sorry guys im just way stupider than you two hahaha
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
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
It finds a vector that is perpendicular to two other vectors
i don't even know if normalizing it has any sense or not
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?
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
got that, thank you both for your time and have a nice day!
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.
use Android LogCat package
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? 🥲
Report it as a bug! I'll test it now
Yep, managed to reproduce this. I get NaN when:
- value is negative
- power is not a round number
Yep - reproduced it as well
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
i is a number to mathematicians, but not to programmers using primitives :p
Yes, that's the right behavior
Oh, okay.
Also, checked microsoft docs, and it says that this is the intended behaviour of System.Math.Pow (which math.pow calls).
Sorry! D:
I think i could just 1.0 / pow(abs(x), y) and get what i need?
That depends, what are you wanting to get?
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?
Yep, that does not work
I'm just messing with SDF falloff functions
power is a parameter you can tune
you don't wanna just constrain that parameter to non-negative bases?
is the base the distance? Negative distances don't make sense
(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)
yeah, i should. i think my brain cooked itself while i was researching this bug :p
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
Yep, abs() this and negate that and i got the intended result. Yay! :D
How can i change the Texture of a Specific Face and get the Texture of a Specific Face of a MeshRenderer?
Faces do not have a "texture".
I don't really understand what you're trying to do here
Are you trying to do per-vertex lighting, maybe?
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
Explain your actual objective here
not "get the textures on a face"
What is the longer-term goal here?
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.
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
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
Hmm i though Unity had really good lightning which doesnt affect the entire face, thanks i guess.
Well, yeah -- if you shine a light onto the object, you'll get per-pixel illumination
Hence why I brought up "vertex lighting", where you only calculate light at the vertices, and then smoothly blend between them across faces
That's a common technique for games that want to look really old
ahh
The lighting is so uniform in this example that it'd be hard to tell per-pixel and per-vertex lighting apart
oh
Maybe you are thinking of flat shading? 🤔
Like sharp edges that are the result of not sharing vertices between faces
yeah
Seems like it
This cube's faces don't share vertices, and you get sharp edges as a result
that's a property of the model itself
oh nice
Okay thanks ill keep this in mind!
🤮
First of all #📱┃mobile
And then you also need to share the whole error details.
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
{
...
}
}
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.
'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?)
can someone help me make a system to save a list in unity for my VR cosmetic system
dm when you can
There's no such thing as resizing a texture. It's basically destroying it and creating a new one, potentially copying the contents. As for difference between texture arrays and one texture, there's basically none. They're both just a contiguous memory block.
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?
As I said, a texture array is basically the same thing as a regular texture GPU wise. You can't "resize" it(neither the element sizes, nor the array length). You'll have to create a new one and copy the data into it. Same as with a texture atlas.
Same for ease of writing. There's not much difference here.
The only difference I can think of is in how they are sampled.🤔
i know you cant technically resize an array. Thats why i put it in quotes
ahh. fair. I'm trying to sample them through material property blocks adjusting the uv coords with texture rects (to preserve a single material)
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
Depends on the platform you're targeting some have a 4k as max size limitation.
PCs standalone, multi OS
Then a bigger texture is probably better than several snaller ones.
Mainly the mobile platforms are the ones having limitations.
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!
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...)
A bit late, but Valve published several papers about exactly how their lighting implementation works if you really wanted to go down that rabbit hole.
Oh they did? Where could i find it?
It has been years since I saw them, so not sure where you could get them now.
Alright ill look, thanks!
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?
Highlight as in selected?
Like when hovering the mouse over the button. If I remember right, selected is used with navigation and gamepads
when unity uses Highlighted Color on the button
you can check if the EventSystem’s raycast hit is a button and the child transform of the panel’s root transform.
hmm, yeah, I think this makes sense, but it will need additional checks, though i think this is fine
thank you
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?'
If you don't have any extra constraints, you must search the entire graph
Depends, you could precalculate this stuff and have a O(1) cost.
If the graph isn't constantly changing, then precalculation sounds like a great idea
It really depends on the context.
You can preprocess the graph to find every connected component. If two vertices are in the same CC, there is a path
It won't be constantly changing, but it will be changing- generally in response to player input
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
And if I can limit it to removal?
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)
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
Hm. So at least this should help the search... looking for pathfinding implementations was... less helpful. :D
it really does just boil down to going through the entire graph
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
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?
Native, as always, means the ball is very firmly in your court
ok, so I have an editor script that does heavy computation on mesh data. I use the Jobs system so I must allocate NativeArrays for like vertices,uv data,etc. The user could select 10k meshes to use the tool on at once, (this is obvs a problem)
but I can't limit it based on the amount of meshes selected, because it depends on the amount of vertices instead.
yep, so you will have to impose your own constraints
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
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
Does changing method from non virtual to virtual causes breaking changes to previously compiled code?
do you have some pre compled code in a dll? virtual methods are called differently so possibly
No, but im making a library and was thinking how to model it in such a way that it is backward compatible
Ah okay, thanks
virtual functions use the vtable to find the function to use at runtime (how they can be overwritten)
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual
Id guess this could cause backwards compatibility issues but perhaps .net can handle virtual or non at runtime just fine
If you have 10k meshes displayed in your game, then it already takes up memory somewhere—if it’s like a reference to a mesh on your filesystem then probably limit it to what the user can view.
Also you can make a resizing array(dynamic list), nothing wrong with that.
The point being If the mesh is displayed within your game(in memory), you could have a native array of intptrs instead
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mesh.GetNativeVertexBufferPtr.html
Yeah, there are different opcodes
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
Reflection works fine on AOT
The only thing you can't do really Is Reflection.Emit
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#)
Are we able to access this? Or would that just be throught hte System.Reflection API?
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?
No dedicated channel for custom SRPs but the Shaders/URP/HDRP channels have the people who are versed in these things.
alright, thank you
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
Perhaps you can just change texture's filtering from linear to bilinear?
(point to bilinear, that is)
wdym?
how would i do that
this is a property of the texture itself
however, we don't really know how you're rendering this thing right now
im using built in pipeline if thats what you mean
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
Is it all done in a shader?
nope its through like 3 different scripts
that doesn't tell us very much...
i mean
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
if so, you need to find a way to actually blend the colors together
not quads
e.g. by setting the vertex color based on the average color around that vertex
instead of using just a single color
that would be too late!
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
Watch a bit from that timestamp. He deliberately uses Point filter mode to make it look more "crisp"
ty but all that really did is make it more blurry
you can still see the quads in between
Not sure what you were expecting then
yeah, that's inevitable if you have a single huge texture
If you want completely crisp edges, you'll need to generate a mesh that follows the contours
or something more elaborate like that
The coastline would be less blocky if you made the water a separate object
Just a simple plane at water height
What does it look like now?
Right. You need to either use higher texture resolution or do something like what Fen suggested
how?
I bet there is a library for applying things like blurs to textures
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
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)
Additionally you can approximate Gaussian blur with multiple box blurs for better performance.
hey kid, want a GrabPass?
want four grab passes?

Is that the technique where you like blur vertically first and then horizontally?
Or something different
Yeah that one.
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
I don't mean that, I mean using actual box blurs.
I can't remember if this is the one, but seems like a good resource regardless: https://blog.ivank.net/fastest-gaussian-blur.html. Do note that it's mostly applicable for doing it on CPU.
ah, I see
The type tree exists on the C++ side of the engine. SerializedObject/SerializedProperty use it under the hood and expose most of its functionality
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
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
Either that or take control over it yourself and set the update mode to manual
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
This is what I've trended towards over time: doing everything in an explicit order
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
Depends what you mean and what render pipeline you use. If you use an SRP, they are open source, you can read and/or modify them.
Mmm so what i try to do is get a method that i can use on a compute shader to apply occlusion culling to GPU instanced meshes. Ideally, something that works in all render pipelines, since so far i managed to get it going
Not sure how you can get an optimal solution without modifying or hooking yourself on the renderpipeline.
Can someone help me figure out why mouse input is not working with new input system. i tried mouse and keyboard input .
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
someone can you help me to figure it out
Already helped you in #🖱️┃input-system - please don't crosspost
ok thank you
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 ...
Nothing that a block of if statements can't accomplish, but otherwise you've got a features like:
https://docs.unity3d.com/Manual/BlendTree-2DBlending.html
Also #💻┃code-beginner
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.
You can serialize prefabs onto scriptable objects just fine
You can use SerializeReference.
has anyone worked with ScriptableObject?
This is code advanced and SOs are just above a beginner level, so I would assume almost everyone here has.
If you have a question about them, certainly ask it and we can help
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:
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));
}
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
First, start from sharing !code properly. Your scripts qualify as big blocks of code.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Aaand, it would be very helpful if you share the error and it's details as well.
What is with Untiy Physics (ECS) rigid objects accelerating on slopes / ramps? is this normal?
unity physics is stateless, so the behavior is going to definitely be different than physx.
and/or any other mainstream physics engine for that matter.
isn't objects accelerating down slopes normal and expected?
can someone help me with some bug i'm having with textMeshPro ?
Not if you don’t ask the question.
it's kind of hard to explain should i give the project files ?
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
A tool for sharing your source code with the world!
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!
thanks il look around
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)?
Put it in a 3rd project that is referenced by both your source generator and your unity project?
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 😅
I don't think there's any other solution
there is one more question that is bothering me
What if I needed in Source Generator information about some built-in class, e.g. Rigidbody? what then? After all, I won't move Rigidbody to an external dll
You use the roslyn source generator APIs
so in my case, my enum Access I can also use Roslyn API, but would it be more tedious, wouldn't it?
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
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?
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
you would make a typewriter effect not by adding text incrementally but by using the "maxVisibleCharacters" property. See if using that already fixes the issue. https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.2/api/TMPro.TMP_Text.html#TMPro_TMP_Text_maxVisibleCharacters
i thought about that but maxVisibleCharacters does not work for some languages like arabic however i did found the problem i need to do _textMeshPro.ForceMeshUpdate() before apply any effects
i did try maxVisibleCharacters tho and it didn't fix it
what you are doing with reapplying new strings is extremely wasteful and terrible for performance
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
it's not really that bad
but sure
i will look into it
please help, why OnKeyPressed event doesnt invokes
This is what my script is referring to.
private void OnEnable()
{
}
private void OnDisable()
{
}
You've got Activate() and Deactivate()
I hope this helps.
Hay, does anyone have any clue how to implement MSAA using the RenderPass/SubPass system in a custom SRP?
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.
Probably this is the same problem I got right now:
https://discussions.unity.com/t/roslyn-source-generator-with-unity-mathematics-reference/934324
but the answer is not satisfactory to me. They just didn't solve the problem with dll visibility.
And this problem also spoils the whole assumption that Source Generator can have a reference to another project/dll, because apparently in Unity it can't.
Please help some good soul 🙏
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?
Yes, enum Access is defined in Polyflair.Codebase.SourceGeneration.Common.
Then I was to use this enum inside Unity project, but also in SG to perform some logic on it. That's why I paste the compiled dll into Unity and I reference the csproj as dependency for SG.
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
The only solution would be to use strings instead of enum, but in my opinion it's hacky solution. If I won't find anything else, I would use it, but I really dont want to :/
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
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.
Already tried many options with platforms in dll and tagging as RoslynAnalyzer, but then I got errors in Unity that I cannot use this enum 😅
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.
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.
what do you want me to try? 😄
Tagging as RoslynAnalyzer or exclude any platform doesn't solve the issue.
What's the error with the label?
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.
https://discussions.unity.com/t/cant-reference-another-assembly-from-roslyn-source-generator-inside-unity/1575986
I've just created a thread on unity forum, btw
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?
Yes, but only in Unity. In third project (xUnit test for SG) everything works perfectly
Because I want access to this enum Access both from SG and Unity
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)
I cannot agree. You can analyze this code, but you cannot use it in SG (types from unity).
You know, you cannot access Rigidbody type inside SG without referencing to UnityEngine.dll inside SG project
That's the same with enum defined directly in Unity. I cannot use this type inside SG.
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.
Well I have some ideas on how I can solve this problem, but none of them answer the question of whether it is even possible to have references to another project in SG, so that SG is usable in Unity. There could at least be such a one sentence in the documentation in the Limitations section if you can't, and if you can, it should be discovered 😅
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...
New Input System or Rewired (asset store)
Upscaling algorithms (on asset store), baking lightning, parallelization of code. Performance depends of many factors, we don't know if you're CPU or GPU bound
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.
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
maybe this is sufficient for them:
asset: https://assetstore.unity.com/packages/tools/utilities/rewired-21676
support: https://guavaman.com/projects/rewired/docs/SupportedControllers.html
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.
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
what does stream: 1 mean for this code example in unity's mesh api https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mesh.MeshData.html:
data.SetVertexBufferParams(12,
new VertexAttributeDescriptor(VertexAttribute.Position),
new VertexAttributeDescriptor(VertexAttribute.Normal, stream: 1));
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
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
can someone help me? my code is acting weird and i dont know why here is a pic:
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
you removed the file extension from your attachments...
and definitely does not sound like an advanced issue
see #💻┃code-beginner
soo I have 3 global rotations ( quaternion )
Hips
Spine
Chest
I want to calculate local rotation of Chest any easy way?
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.
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.
There is this internal class:
https://github.com/Unity-Technologies/UnityCsReference/blob/129a67089d125df5b95b659d3535deaf9968e86c/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs
It might have some more detailed information.
The singleton instance is accessed from here:
https://github.com/Unity-Technologies/UnityCsReference/blob/129a67089d125df5b95b659d3535deaf9968e86c/Editor/Mono/Scripting/ScriptCompilation/EditorCompilationInterface.cs#L15
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.
Thanks, I will check these out for possible options.
I had doubts about OnInitializeAs well, but that operates through the active assembly, and so it should only be a potential issue when first loading the IDE and there are code changes to compile. I don't know if it figures it out for that, but will be easy enough to test for once.
The fact that it checks against a hash, (which can be the same principal as a CRC on the file) is the blocker.
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.
From reading the forum thread, have you looked into source generators?
Yeah my bad, in the first iteration the compilation event wont be trigged but for next ones it will. 1. compilation 2. domain assemblies reload 3. subscribing event to compilation [InitializeOnLoad] then when source code asset chanhe it repeats the process so the event fire for compilation and its wiped out.
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.
CompilationPipeline.assemblyCompilationFinished does capture it, and storing it to an editor pref allows me to hold on to that state. It captures every time, except when a compile doesn't occur. (and possibly when the IDE first laods)
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
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.
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
using Roslyn it's pretty trivial as Roslyn can return the source code of the classes in the .dll. So then it's a simple line by line comparison
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
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!
How to Write Gyroscope Controller with Unity3D
Unity terrain is a good start as you can give it custom height data from elsewhere such as noise and some custom processing. You can also set the splat map for the terrain shader or do your own using the same height data to give the results you want for the water edge
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?"
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
If your painters are pretty small (like 3 "steps" of the player), it seems like just playing the sound for the closest painter is fine? Like, if you're a couple steps off of the stone on the grass in your screenshot, I don't think I'd notice or LITERALLY UNPLAYABLE the game if it played a stone footstep on the border
(or just grass if there's no painter within 3 steps)
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
(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?)
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];
}
mhm, you can see an example of one here with the debug ball turned on
Yeah, that's probably what I'd do then - just KISS it and move on to the next task probably
so i just need to write something to determine the "true size" of them and then it'll be good
yepyep
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")
Not an answer, but I didn't know records worked in unity? I thought that was a relatively recent .net addition
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);
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
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
Ah, cool
using the declaration I showed earlier works fine for me. Didn't encounter any issues yet
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
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
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.
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
Yes, it's always the same
This is the most recent thread I can find on UGUI custom shaders - https://discussions.unity.com/t/grayscale-and-colorize-image-support/763843/7
Where can I chase down this feature-ette and see the latest progress on it? Ideally, I don't want to install a custom shader library just to make a few images monochromatic.
(I've used this in the past: https://assetstore.unity.com/packages/vfx/shaders/all-in-1-sprite-shader-156513 - and it's just super clunky)
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.
I don't see how it would be different from profiling and optimizing any other code
Optimize as best you can out of the box, and be responsive to requests/issues.. Frankly that's mostly why people (or maybe just me?) buys assets - not because it's some magic that I'm not capable of, but because it saves me time.
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)
i should've specified: it'll be free. I want it to be an impressive project in my portfolio (technical artist)
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
I would not publish the asset on the store then. That would be a waste of your time.
you could always toss it up on Itch or something similar
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"
Following the guide here: https://docs.unity3d.com/6000.0/Documentation/Manual/create-source-generator.html
it says:
Install the Microsoft.CodeAnalysis.Csharp NuGet package for the project. Your source generator must use Microsoft.CodeAnalysis.Csharp 4.3 to work with Unity.
Does this mean exactly version 4.3, or 4.3 or newer?
I ask because 4.3 has been unlisted. https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp/4.3.0
You probably still can use older version.
I used 3.8 for Unity 2022.3
Install the Microsoft.CodeAnalysis NuGet package. Your source generator must use Microsoft.CodeAnalysis 3.8 to work with Unity.
https://docs.unity3d.com/2022.3/Documentation/Manual/roslyn-analyzers.html
Right now I'm trying to get any version to work
I'm not married to an older version
this code generates terrain from heightmap, has a vertex-distance parameter for accuracy. works fine unless you put the vertex-distance under 0-1, you get a corrupt output mesh. im not sure why, i think its a indexing problem in either of the for loop.
https://pastebin.com/x4179EYw
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
No, you'll have to debug the code. 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?
i did for 2 hours
im pretty sure its an indexing problem but i cannot find out why
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?
is that better?
What debugging steps have you taken and what were the results
changing the code over and over and overthinking the logic. there'snt a debug stuff this isnt a game. its mesh generation.
Debugging is the process of examining, analyzing, and testing your code to figure out bugs
it has nothing to do with games
You can and should debug any code you write that isn't working.
there's nothing to debug with mesh generation. its like debugging skinning. you fix your logic.
You are completely wrong about that
It is code like any other
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
This is not a machine learning model
this is like that but a bit less verbose
I just explained how
Here are some techniques you can use
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
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?
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?
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...
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.
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?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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.
And in that time, you didn't write a single debug.log()?
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
You should contact the makers of Animancer for support
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
well, you might get lucky and someone decides they want to make a thread and support a third party system. good luck
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?
https://github.com/ShanguUncle/UnityChatSDK perhaps this?
[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
You're probably changing the collider such that the collider is overlapping with the ground
suddenly the physics engine tries to depenetrate them, launching it up.
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?
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)
your generator doesn't implement the ISourceGenerator interface
🤦
I have a working Source Generator, they are real fun
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
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.
I see you are using CodeAnalysis v.4.3.1 iirc the docs recommend 3.8
4.3.1 is the version bundled with unity 6
well 3.8 works with 6 as well
yes, but 4.3.1 has more features, like incremental source generators
Different versions of the docs recommend different CodeAnalysis versions.
The 6000 doc recommends 4.3.0, which is actually unlisted, VS installs 4.3.1 when you try to install 4.3.0
Anyway one of the many troubleshooting attempts I made was to try several different versions and none were working.
4.3.1 is working now.
Have you tried the Syntax Receiver yet?
thats next then, have fun, DM me if you have problems
@thin mesa have you made one for Unity 6 ?
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...
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
I'm reading through this now which seems like a great resource https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.cookbook.md
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
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.
I did something pretty similar. my setup is kind of cursed though tbh
https://paste.mod.gg/dzecsaryexol/0
i've got the syntax receiver to find classes decorated with the SaveData attribute, then it searches each member for a Save attribute and creates a struct as well as save and load methods for each type. there's probably a lot i could clean up with it, but it works 🤷♂️
Did you find that it impacts compilation time much more on unity 6 than 2022?
thanks for the example 😄
not particularly 🤷♂️
this is mine. It's made specifically for my serialization system but the logic should be transferable
https://paste.mod.gg/pwljojbjrjrs/0
A tool for sharing your source code with the world!
I like that you went the partial class route as well, great minds think alike
Thanks for the examples you two, I'll be back if I run into trouble.
honestly makes things a lot easier since i could add methods for saving/loading directly to the class
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
gimme a sec and i'll have an example of an incremental source generator for you too, just gotta copy it into a bin site. this example even includes relevant analyzers
What's the benefit of an incremental generator
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
here's my incremental generator for creating a property with an event invoked when the value is changed from an attribute on a field: https://paste.mod.gg/qczdeyokvzje/0
oh yeah, that also uses my shitty little string extension to remove prefixes and capitalize the first letter: https://paste.mod.gg/tmtzfoqtnxeh/0
It seems a shame, all that effort to write a nice save system and then you go and ruin it by using json
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
has anyone used the graphql clients from https://github.com/ChilliCream/graphql-platform
@thin mesa how do I get it to only generate the code in Assembly-CSharp (or I guess some specific assembly)?
pretty sure you need assembly definitions to limit its scope
https://docs.unity3d.com/6000.0/Documentation/Manual/analyzer-scope-and-diagnostics.html
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.
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.
From my limited experience, what you described is definitely possible with a "regular" source generator. No idea about an incremental generator.
My understanding just from the names is that the regular one will run on every compilation generating the source file every time
I think yes the incremental generator is essentially a performance optimization over a regular generator
I do love me some performance
Incremental SG also runs on every keystroke in your IDE just like an old school SG, the difference is that the generation process is split into steps, and latter steps are skipped if a prior step outputs the same results as cached results.
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.
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
A tool for sharing your source code with the world!
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;
}
}
}
!code please
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
done
Can you explain a bit more, what "It doesnt" mean in your case?
lemme record a video, easier to show then tell, ty for helping
I found this while researching https://github.com/pakrym/jab/blob/main/src/Jab/CodeWriter.cs @sly grove checkout the code writer might be useful to you too.
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
It's generally not necessary, since SG runs on dev machine so it's way less resource constrained, generating a few KBs of string garbage is far from end of the world.
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.
I would agree 100% with that, having tried both routes the interpolated string one makes for much better code
Good to know
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
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:/...
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:
can you post your code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hmm, that's empty
how ironic @sly grove needing to be told how to post !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
rofl
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
smh using java in unity
Is it because I did context.AddSource("GameDataInterfaces", Interfaces); instead of context.AddSource("GameDataInterfaces.g.cs", Interfaces); 🤔
see what I meant when I said this shit is difficult to debug?
yes
that will do it, yes
you need the .cs so it's picked up by the Unity .csproj generator
I blame Unity's documentation example https://docs.unity3d.com/6000.0/Documentation/Manual/create-source-generator.html
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
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'
what folder is your dll in?
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
plugins didn't help - I'll take a look at the csproj
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
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.
Before I put the DLL inside an asmdef it was running for every single assembly in the project including not only Assembly-CSharp but also every plugin, package, and library,
Rider autocomplete was happily suggesting 25 different copies of my generated class
indeed, very slow and unnecessary
Indeed my GameAssembly.csproj file does not include the generated files 🤔
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.
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>
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 🤔
this sounds like a wonderful idea
I'm wondering is this an artifact of 4.3 instead of the 3.8 I'm using
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
Building the DLL in VS didn't fix it
that syntax would tend to suggest that there is only one context assembly whereas with asmdefs there could be many
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
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
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.
Something not working as expected.
2 identical classes, first in external .dll second in Assembly-CSharp
first does not generate, second does
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?
also, pro tip (hmm), having the Trace method there allows me to right click and 'go to definition' to see the generated code
as in
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.
Bit of a give-away, not in the csproj file
no, not in VS, which kinda makes sense as the generated code is not in the actual project
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.
you are absolutely right
this is VS 2019 btw
that is cool
Yeah, makes debugging what SG actually generates quite a lot easier.
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.
the happiest outcome of this exercise is that you learn why each of these architectural elements is actually not improving much and how you can simplify it in the future making a much leaner and easier understand codebase that others can cooperate in. So i'd say try both options and go all in, this will have the biggest payoff.
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.
Well, I don't really have that option, lmao - this is a professional project, that I have... technically the biggest Unity-related seniority in? The event bus has been setup by someone else already, someone who isn't working here anymore. But the project is still relatively early, so setting up a proper structure for everything is very possible
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
alright, in that case, if i were to advise in a commercial capacity, i would suggest you only do things that you already fully understand why you need them
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)
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
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.
I WANT to try it, but I've never done it on this scale, so I'm asking
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.
whether you split ui and logic into separate assemblies depends on what kind of ui that is, typically you would put all your library stuff in one and your project specific stuff in another and only if it gets too big split again into subassemblies.
we have a pretty advanced eventbus, which can carry data and has an ability to coordinate multiple events in a pretty nice way (a big event stores multiple smaller events that can do their own processing if needed), while also having things react to it post-processing
are you working on a mobile live service game?
It's all project-specific, both the managers and the UI, although we're trying to make those components as reusable as possible for other projects
how many people in the team?
not exactly live service but that's a good guess lmao
soon to be 3
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.
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
can you elaborate on what a the properties of a well designed one would be and how it creates this freedom?
we do have all of that, yeah - and we're planning for it to be a semi project agnostic base for future projects as well, so perhaps it is indeed the way to go
oh I already love the event bus lmao and I haven't worked with it for that long
I just wonder how far to take it when I'm running with it
like you said
@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.
damn that sounds pretty interesting, I'd love to take a look at your event bus lmao
can you be more specific, this doesn't really inspire much confidence vs. the everyday issues i see in projects.
I will probably use an event bus in every single project I make, because it does solve a crapton of problems, that's not the question here
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 !
I see.
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.
I was just about to ask how do you ensure type safety. I guess the answer is you don't?
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.
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
I don't see how that has any type safety, what stops code from calling GetContent<NotTheCorrectTypeForThisMessage>()?
well, we have a wrapper for an event group, you call that, but you can only recieve Events
the fact that it won't work
I mean not work properly
@scenic forge interesting. our type safety isn't set at event level, but at subscription level.
Explodes are runtime sure, but that's not compile time type safety.
Velcer said it doesn't have type safety but their full system does
So the method recieiving this event would already be self aware.
are we talking about event bus for network distributed services or about a model for implementing process-internal logic?
I'm talking about process-internal logic
@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.
interface, not base class, my bad
a pretty empty one, it just has a single apply function in case you want to do some processing
How does the emitter know to set the correct content, other than manually keeping it in sync with the receiver?
making it more generic IS very cool, but you still need to define event types somewhere, right?
Sounds like how mine is set up as well. Here it is if you want some inspiration:
https://github.com/PeturDarri/GenericEventBus
how do you do it?
I do it by defining classes inheriting from a common interface, each class being an event type
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.
solved a lot of problems
sorry for the silly joke, but username checks out lmao
Yeah this is closer to what I imagined a type safe event bus would look like, providing type safety using the type itself rather than a string key that has no relationship with the payload.
@scenic forgeoh, string key? trust my I do way worse
what could possibly be worse than a string key?
XD
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
That's... really interesting actually, but not really good for my purpose, as that partial class would mean I can't decouple it into separate assemblies
first time hearing about this wtf
best you immediately forget they exist 😉
No, they have their place.
Everywhere in my codebase.
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.
With this system, all of them should reside in the same file.
wait what, I really need to look up what that attribute does
You're correct, it does have limitations.
@turbid tinselLineMember returns the line, caller name returns the method name
the line
this
this line?
yep
god this is cursed
yep
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 😄
this is insanely cool. But you are not telling me this somehow depends on CallerLineNumber internally.
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;
}```
Caller member name is just a string but worse
caller line number is the most cursed thing I've seen in a while
it's very useful
I bet lmao
you just have to get passed your internal bias
it's like love
just at second sight
the internal bias of maybe modifying my files someday?? 😭
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
it's a partial class though, it can overlap, can it not?
someone mentioned that here already
partial class isn't necessary. I only did that because I wanted to seperate my logic from my types.
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
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.
Ah, a big benefit I saw to using a partial class for this is using it across multiple files
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.
don't worry, project becomes success, I sell
But the use of line number for message types is too limiting and dangerous, in my opinion.
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
you can combine caller member name with the line number and get a unique hash code.
You can also combine class name
yeah. I'm scared and I'm going home actually
That's what I thought you were doing first and that would be better. There can still be hash collisions, but then you could just throw an exception.
@turbid tinselfor more safety, you can use stack trace to ensure that your message types are original.
I don't even know how I would do that but that doesn't sound less cursed
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.
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!
If you execute a shell command /start a process and wait for it, you are making the main thread wait for potentially seconds untill the process exits. This will destroy your framerate and cause stuttering.
This needs to always be done either async or on another thread.
You have 0.016 ms per "update" but if you introduce a 500ms + pause then ofc you will get problems.
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())?
no, p sure this is the first one I attached:
var task = Task.Run(() => dt.Func());
yield return new WaitUntil(() => task.IsCompleted);
that's in a coroutine
afaik that should start a new thread for that process and the second line should basically check if task is complete each frame
Yes that will. Have you done any profiling?
yeah, I honestly couldn't find much but my profiling skills are limited to say the least
You want to identify frames where it took longer to complete (a spike on the graph). You then inspect what took longer (enable deep profiling if needed)
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
WaitForPresent means that CPU waits for GPU.
I am finding this extremely odd tbh, is it possible that just rendering a single tmp text and 3 labels w ui toolkit is that bad?
because if I disable them, and let me make sure, it doesn't drop anymore
Obviously should behave much better
(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?
is 24 considered giant?
No, that should be fine.
Both capped to 120fps to avoid gpu overuse
- With ui
- Without ui
It's so beautiful 🥹 thanks for your help with the source generators @thin mesa and @upbeat path
welp I rebooted my pc and it appears to be working fine, great, thanks for your help either way 💀
Nice one, fun isn't it
As an aside (I read the above thread - good stuff) - is there a way to get random files included in the csproj files consistently? I want to edit my html templates (in visual studio) but I have to go outside unity to open them with VS, and "show all files" in the solution explorer or CTRL + ; in visual studio works sporadically
On this topic I am unfortunately clueless.
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?
nothing crazy, just a save data/serialization system for my current project. I seem to build a new system every time I make a game, in search of perfection I suppose.
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
Basically generating flat DTO types corresponding to my game model objects to be serialized with MessagePack
Not gonna lie.. one of them involved .ini format files
(that may have been the worst)
This was my cosmosDB and networking solution - worked the best imho
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
I'm seeing if codegen can alleviate some of that tedium and error-proneness
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
That's actually lovely and I can't think of a much better way to do it 😆
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
This looks like the outcome of a not very well thought through class setup OR its just that complex and you need it 😄
This is what I wound up doing in a browser game written entirely in Javascript
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
I had an array of migration functions that took you from X to X+1
Especially for an MMORPG
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)
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
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
no need to take it personal. It was guessing and you only read the first part, not the OR part, which actually stated, that it is that complex (in changes or setup) that it needs that hardcoded update 🙂
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...
Not taking it personal 🙂 just meant that .. it's hard to come up with DAO/POCOs that are resistant to change and flexible to change at the same time :p
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
only the serializer would need to care about specific versions
you wouldn't let that stuff "leak" anywhere else
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)
my heart briefly sunk when I spotted "99+ references"
but that IS the player's GUID 😉
so all of the hydration methods have to scrub the files coming in and going out
not the worst thing to be heavily-used
so there's an internal id and an external id :p
(and then the database required it's own naming for a guid)
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
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)
(In TS, you can do some cool stuffs that enforce each step of the migration goes from X to X+1)
I should probably base64 these instead of storing hex strings
or go to a binary format
Where I work we use protobuf for our configuration and player data.
I've always known about protobuf, but I've never actually poked at it
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.
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.
I like messagepack for it but.. only because the protobuf documentation seemed inscrutible at a glance
(I also like the dude who made messagepack)
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).
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?
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
Nope. If you plan to use Unity's built in physics, your options are SphereCollider, BoxCollider, CapsuleCollider, and MeshCollider.
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
yeah looking like still no... despite the confusingly titled "custom physics shapes" heading
you're probably looking at doing custom physics
so annoying, how is there no way to define if a collisions occured or not?
BetterPhysics from the asset store 😄
that has what im looking for?
I am the author of that asset and it certainly does NOT have what you are looking for lol
dang, right from the source lol