#archived-code-advanced
1 messages · Page 110 of 1
It worked, thank you so much man
also I checked out your slime game in your dicord bio and it's pretty coo, good job
Is there anyway I can get the compilation command that unity uses when it recompiles after detecting changes to the code?
I assume it's using mono
Would also be nice to know the path to the compiler unity uses
Well, I found mono
Hey all,
I have an issue and I couldn't find a solution yet.
That rod animation and the line physics are not synced. Line logic is in FixedUpdate and Rendering that line is in LateUpdate.
Also first particle of the line is always same as tip of the rod position and it is in FixedUpdate.
I've tested to put it in the Update or moving rendering to Update or FixedUpdate but still the same issue.
I changed the Animator Update Mode to Animate Physcis too and by updating first particle on the line to be same as tip of the rod in the update it is kinda synced (Though weird thing happens on the line) but I'm not sure if it is a good idea to change the Update Mode to Animate Physics on the animator because probably it is always based on the FixedUpdate time scale.
So any idea on that ?
@earnest heron
If you tried changing update types:
The transform.position and rigibody.position is not synced. They may be completely different at the frame. Rigidbody.position updates the transform in the next fixedupdate. At least this is the case for new version of Unity. You need to decide whether you will use the position for physics or visual. If you using a position for visuals, use transform's position. Update order is defined by the way you code your scripts.
Hi friends I am generating the FBX model at runtime but there are duplications of a single mesh appear, multiple mesh filters contain the same mesh but when I generate the 3d FBX file, it generates separate mesh for each mesh filter even if they are the same meshes, how to solve this by developing only one shared mesh. I am using this asset for exporting at runtime https://assetstore.unity.com/packages/tools/modeling/ascii-fbx-exporter-for-unity-231226
Please share if you have any other asset or method to export FBX at runtime, Thanks!
I don't use rigidbody on that line at all. It is Verlet Integration in FixedUpdate.
Hi, do you know how to run async Awaitable method from non async method?
I don't think that just calling
_ = MyAwaitableMethod() will be working properly.
Well, no idea then. This is how i solved when i encountered this issue.
Mm... FixedUpdate happens "before" Update, so this means you update the line first and then the animation (the position of the rod). Also, keep in mind that you may get Update without a FixedUpdate, in which case obviously the line would be off.
You should probably update the line on Update. (At the very least, it's "root" position, and maybe not do all the logic 🤷♂️ )
He said he had implemented this by custom verlet integration. What if he does some kind of velocity smoothing for the start point there?
you CAN do that but you generally shouldn't, discarding the result means if an exception happens it won't be logged! if you really need a fire and forget async call, it's best to make an async void method and call that
Ah for addition, async methods are harder to debug still. Wonder if they fixed the long hierarchy in new version...
You can have your physics update in FixedUpdate and simply lerp towards the result for your visual.
I see.
Right now, I'm trying to use physics particles array and assign their positions to a new array and reset the first one to the pin position on the rendering function (LateUpdate).
But just doing that makes the straight line between first and second particle which makes sense but ugly (Also it is synced with animation). So to avoid that I'm trying to generate new vertices in between. Is it a right approach ? Though I'm not sure how to smooth that yet. Maybe I should use 3 point Bezier curve ? Or I can achieve that in much simpler way like you said about lerp ?
This is really driving me insane, and I've tried to fix this a number of times over the past year but failed.. Visual studio just occasionally "detaches" from unity.exe and breakpoints are no longer able to be hit. I've googled the hell out of this, and have updated to 2022.3.40 (but there's no mention of this being fixed in any of the release notes).
There doesn't seem to be rhyme or reason to it.. I'll be working just fine, stepping through debugger, then randomly the breakpoints all cease to work and restarting unity/vs have no effect.
Has anyone seen/fixed/workedaround this? It's making working on tricky code patches .. doubly tricky.
I cannot really help you there, I have not really experiemented what you are trying to do. The only thing I know is that usually when you do things in the FixedUpdate, it is better to follow the result then using it straight up.
I have the same issue. It happens periodically, but usually restart computer solve the issue.
Yup, that's right. I got that point today when I was experiencing with different approaches 😄
I tried that in the past and sometimes even that doesn't help.. And it sucks to be debugging and then reboot and restart unity (which takes longer than the actual reboot tbh)
Hi
I've gone so deep on this googling problem/solutions.. even going so far as to reset my network adapters, thinking it's related to some sort of failed tcp/localhost socket
Are you debugging local ?
Or it is a console/mobile device.
Anyway, whenever I have the issue it seem to be related to process that are still running in background. Might not be the same issue you are facing.
local
Doesn't seem to happen for my other projects in unity6, but those aren't as complex as this one for a client using 2022
Like, this project is huge... several thousand .cs files, plugins, packages, etc.. unity form posts asking for a repro project are just .. impossible to really do for this (NDA notwithstanding)
I've tried regenerating project files, restarting editor, visual studio, computer, starting and stopping other instances of unity editor (thinking maybe there's some sort of network teardown or setup that's failing?) .. can't seem to get a consistent workaround to enable breakpoints
Do you have any other computer ? Sometimes, it happens to my computer but someone else is able to debug without any issue. (In remote debug though)
Not that's setup for this client, just a macbook pro which is a bit hard for me to develop on
I've also tried starting/restarting VS in admin mode, reattaching directly to the unity process..
Like, digging up the PID of the unity.exe that's running the game, and attaching to that pid in VS
Are you able to profile ?
In unity? I imagine so?
Is it in editor ?
profiler works fine
But that probably won't help me for what I'm debugging.. it's a little complex but I need to step through the code for this
You are trying to debug the editor or a build ?
Have you tick the box that enable you to debug O.o
but i'm not debugging any editor code (like custom inspectors or anything like that)
where is this magic box? 😛
Oh, yeah, that's checked.. I mean, it works "fine" for a while and then just randomly stops
I thought you were joking and saying "just click the button that says 'make the problem go away'"
No idea.
because I would pay $$$$$$$ for a button like that..
Only times it happened, I restarted computer and was able to debug again after.
I don't even think those checkboxes matter since I'm not doing a full build, just running play mode in the editor and trying to attach VS to unity.exe
but what do I know 🤷♂️
Yeah, that was my point if you were doing a build or not.
Have you try doing it one and see if it works ?
Also, I imagine you tried to flush library folder
i did the library rebuild a while ago for this, but won't do that again since it takes about 30 minutes for this godzilla project
I dunno - I'm not even opposed to learning how to use Rider if it works consistently. Haven't used it enough (I have it installed on my MBP) .. how do y'all debug/IDE (on windows)?
I'm currently trying nonsense that is found on like the ... 0 upvoted solutions on the 10th page of search results from SO like "change the api compat level to/from whatever you're using"
Rider/Visual Studio are pretty much your only option. You have Visual Studio Code, but I would really recommend.
Rider is not free though
Yeah I'm not gonna use VSC.. I use it for other text editing and can't imagine trying to debug with it.. I'm sure it's possible but .. I dunno
It's not any different from VS debugging, you have conditional breakpoints, stepping, viewing stack, variables, etc, all the same.
So after an hour of tinkering, upgrading VS (and all the extensions that broke because of.. things), the best workaround I can find is to ensure that the breakpoint is set on a script that exists in the current sceie/hierarchy. There's some magic about how VS is finding the location of the code and.. it's not always working unless the object exists in the scene. From there I can step through it.
It's a pain because the entire service layer is lazy instantiated through a DI framework so I can't put any breakpoints (it seems) in that layer.. I have to put them on the view layer objects and then chase it through the service layer code.
Anyway, FYI.
Afterall I could sync my Verlet Integration (On FixedUpdate) first particle position with the pin position by applying pin position to the first particle position before rendering and on the LateUpdate but as you can see there is cursive line between first and second particle (The reason is first particle shifted to the pin position but second particle calculated based on the Verlet Integration and before reseting to pin position on the LateUpdate).
Any idea I can fix that ? I tried to use Bezier Curve between first and second particle by extra vertices but it was werid.
And you're not doing the verlet integration in Update because?
Generally, you need to smoothen the whole thing, probably... or at least apply some smoothiness to a few of the particles
It is physics based approach so it doesn't make sense to be called in update.
Yup, that's the idea but I couldn't find a good solution which doesn't make it weird. I really like the rendering on the particles but it was annoying it wasn't synced with the pin point and now that cursive line is annoying.
hello, I'm having an emergency and need some help. I haven't opened my unity project for about a month and I have uncommited about a month of work on it. I downloaded a new unity version and when I try to open my project it's stuck on Register Scripts. I look at Git and all the GUIDs of my project have changed and it allows me to open a copy of my project which I've used Parrel Sync for but it's completely broken because of GUID changes.
Please I need help with this.
Step 1 is to feel the pain of this and let it be your teacher. Never go a month, a week, or even a day without uncommitted changes. You can press commit and git push in like 8 seconds, even for half broken shit you're still working on (branch and merge).
I don't know what Parrel sync is, but .. I'd probably advise that Step 2 should be to immediately copy your entire project folder somewhere else on your machine so you can start trying various things.
Step 3: probably install your old version of unity (you can easily have multiple versions with unity hub) and try to open your project with that.
Step 4: is to write out the pain of Step 1 and put it on a post it note and stick it to your VIP space on your monitor, because the pain of what you're feeling and what you're about to go through either fixing the problem by hand or recreating a shitton of work is something that's completely preventable in the future. 😦
definitely don't do something like attempting a version upgrade without making a commit first!
Save early, save often
Another thing you can do is rename the existing directory and re-clone
Sometimes help migrate things over, worst case scenario
Litterally the only thing you could possibly do here is manually copy the guids into the meta files manually
Why they would have changed is odd unless you were doing Unity upgrades before committing changes. If you're unsure of changes you may not want to keep, just commit them to a side branch just in case.
I’ve been doing that and suddenly it says the last opened version is one i haven’t used for like a year
I downloaded it and manually changed ALL the guids and it seems to be working!
Now I can commit and try and update to the latest version
Glad I didn’t lose a month of work🥳
hello, in unity editor, to free cam, you have to press right mouse button + wasd keys.
is there a way i can make this a toggle ? for example: pressing f1 will allow to move using wasd. pressing it again disables it.
settings ViewTool to ViewTool.FPS doesn't seem to enable wasd move
#💻┃unity-talk
this is not a code question
how do you figure that?
figure what ?
that it is a code question
im the one that decides that
no you are not, the people answering the questions decide that
there's no toggle.
in editor, setting Tools.viewTool == ViewTool.FPS doesn't emitate that.
not rly.
but sure
I've got a monobehaviour that executes in edit mode which has a compute buffer. This is working fine on runtime, but on domain reload in editor, it leaks persistent allocations.
I'm releasing the buffer in OnDisable, which is likely why it's behaving correctly on runtime. How can I make sure the buffer gets released on domain reload in-editor?
simply adding the buffer.Release() to execute on callback from AssemblyReloadEvents.beforeAssemblyReload seems to not consistently solve the problem. Specifically, I've now noticed that if I enter play mode, exit play mode, and reload the domain via script change, it's still leaking
But if you have exited Play mode, surely your OnDisable should have handled that, there would be nothing for the reloadevent to do
the monobehaviour has the [ExecuteAlways] attribute because it handles rendering an effect, both in play mode and in edit mode. So I figure when I exit play mode, the OnDisable gets called, then OnEnable gets called again
which shouldn't be a problem, because OnDisable should be getting called via AssemblyReloadEvents... So I'm a bit at a loss
I can't remember the exact sequence events in this situation, it may be worthwhile chucking some Logs in there just to be sure
thanks for pointing me in the right direction. It 100% was just a method on runtime that was creating a new buffer without clearing the old one, it was just only getting logged as orphaned on domain reload so I thought the domain reload was the culprit. Thanks for the help!
excellent
Unsure if this is an "advanced" code question but:
I'm working on procedural generation using a Wave Function Collapse, can someone point me in a direction to figuring out how I'd go about implementing tiles of varrying sizes?
wave function collapse is just averaging between multiple noise layers right?
if so most of the time you can just scale tilesize by multiplying the x/y seed of each noise layer with a multiplier
The actual way it works is a bit over my head. But essentially its an algorithm that uses prefabs and constraints for those prefabs, and stiches compatible prefabs together based on the constraints of said prefab
At least, thats how I understand it
would anyone happen to have any resources for making a frame-independent input system in unity? unity supports C/C++/Obective C plugind, but from what i can tell, you can only CALL functions from them, and of course only from unity's frame-locked C# stuff
i'm specifically making a rhythm game, so precise input timing is very important
please ping me if anyone responds
You can manually poll the input system as fast as your hardware allows. Unity also does not force you to use the engine callbacks (update/fixedupdate) or any set frame rate. These are just defaults you can use for convenience.
So I'm trying to set the position of the player transform directly and it seems to be causing weird race condition issues. If I put the trigger in LateUpdate is sometimes works correctly, whereas it just doesn't if I do it in Update or OnSceneLoaded(). I suspect it has to do with the character controller, in particular this line:
// move the player
_controller.Move(targetDirection.normalized * (_speed * Time.deltaTime) +
new Vector3(0.0f, _verticalVelocity, 0.0f) * Time.deltaTime);
If I inspect the Character Controller's Move() method, I am met with a really bizarre method of handling this, in the form of Collision Flags, which was not at all what I was expecting. I expected it would move the transform directly in response to collisions combined with movement data:
public CollisionFlags Move(Vector3 motion)
{
return Move_Injected(ref motion);
}```
Has anyone else been experiencing this issue and / or know what to do about it? I can seemingly get rotation to work just fine every time. It's only positional data that's the problem. Please ping me if you have any thoughts on this.
Thank you so much. That makes perfect sense.
Im unsure what you mean by the second part; yes, technically ypu dont have to use update, but that would be the only way to consistently check for inputs, right?
Even ui elements like buttons dont register inputs until the frame updates afaik, so i don’t see a way to call any function “in-between” frames, regardless of the frame rate.
well if you want a game that operates on some sort of tick, you can use unity's FixedUpdate and set that to this desired tick rate. This gives you a relatively stable and predictable render-independent loop at potentially very high frequency, (so long as you don't use it also for physics simulation). You can then set InputSystem to process inputs in fixed update. Alternatively you kick off your own custom update-loop with your own timing control and call InputSystem.Update() manually.
You could also start a loop in a new thread and update it as fast as you want. Though then you'll have to deal with multi threading issues.
Also, I remember reading that the new input system is frame rate independent and precise. Could be wrong though, as I still haven't got to use it properly
Hmm, i’ll look into those.
Also keep in mind, framerate is for displaying the graphics to player, your game logic doesn't have to run on the same rate (albeit most games do structure this way)
Let's say your input hardware has a 240 Hz, but your display is only 60 Hz, that means for every frame of display there are 4 frames of input. It doesn't matter whether you spread out processing those 4 frames of input evenly in that 1 frame of display's time, or you bunch them altogether right before the frame is drawn. As long as they are all processed, it's indistinguishable to the player.
you can also just collect your events in regular Update and use the callback context info to unroll the events that happened over the past frame, this struct has raw input timings iirc
you just gotta disable event aggregation
Oh yes i’m aware, im just familiar with the fact that monobehaviours Update() once per display frame, so those four “input frames” would all be processed at the same time if done in Update(). In a rhythm game, its very important to have inputs as precise as possible (diagram by Evbo of Tempo Lab Games) so i wouldnt want any input frames to be squished.
Oh nah, that's not how you would do input handling in a rhythm game.
If you judge player base on frame time, that's already wrong.
New input system package has hardware timing of when the input actually occured, you will judge player base on that, not the current frame time.
Er, yes, thats what im trying to avoid 😅
you use that, you subscribe to the event, it gets called independent of framerate, potentially multiple times per frame, depending on how you configured the system https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/api/UnityEngine.InputSystem.InputAction.CallbackContext.html#UnityEngine_InputSystem_InputAction_CallbackContext_time
Depends on what platform you are targeting, if it's for example mobile which touchscreen has a pretty high input latency, you will have to do some form of rollback (albeit very simple ones)
This is for Standalone Windows and MacOS
you can also adjust the internal polling frequency https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_pollingFrequency
Well you don't need to worry that much about doing a rollback then, you just need to shift the timing window based on player's input calibration, and judge player based on hardware time shifted by input calibration, and that should be it.
This doesnt really sound like an advanced issue. More like #💻┃code-beginner or #archived-code-general
It sounds like your players just need a reference to some dice to roll it. Or some game manager rolls the dice and tells the player how far they can move.
Sorry
Can I ask a question about vertices data into byte data with a binaryReader? I am having issues with it and cannot solve it
My issue is the script intending to read the vertices data from the target object is sending over the byte data but for some reason the script meant to desearilize the data is now way off, like several thousand vertices for a test object that clearly couldn't have that amount. Something is wrong, and I don't understand what it is.
surely with a binary reader that would be the other way around
I am using a binaryWriter to get the intended byte data from the target object, than I double check it in the same script showing no issue. However it for some reason gives me a completely wrong data set for it in the script receiving it. To make it even more confusing the same script I did for the the other data I need from the target object, like the quaternion is transferring just fine with zero issue despite the same exact code??
Should I switch to Jswon data transfer instead of doing bytes? But I am doing very large data sets that are custom player built with hundreds if not thousands of custom vertices, vectors, color, and other needed information.
If anyone has experience with this please give me guidance, or a direction to go. I am lost right now and my project I am doing is in standstill waiting for this one issue.
it would help if you shared your !code both for the BinaryWriter and the BinaryReader
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
I didn't want to ask someone to do my project for me, I don't want to be misunderstood that way. That is why I avoided it, but I will share it if you would like to see it. I did use AI chaptgpt to teach me most of this since there was only 2 youtubers teaching binary data in c# for gamedev I could find.
This is my serializing script that gets the target data and then sends it via byte to the other script. https://gdl.space/jocucozana.cs I believe it has zero issues, and I have higher confidence in that script then my deserializing script. https://gdl.space/quxiwapela.cs
The vector data was the issue, I am sorry for causing any misunderstandings. My head wasn't clear and I said the wrong term before.
any ideas what my problem is?
I did use AI chaptgpt
yeah, there's your problem
AI isn't an all knowing god. It's wrong a lot of the time.
{
//Validate transform values to avoid NaN issues
ValidateVector3(transform.localPosition, "localPosition");
ValidateVector3(transform.localScale, "localScale");
ValidateQuaternion(transform.localRotation, "localRotation");
WriteVector3(writer, transform.localPosition);
WriteQuaternion(writer, transform.localRotation);
WriteVector2(writer, transform.localScale);
}```
``` private void ReadTransform(BinaryReader reader, Transform transform)
{
transform.localPosition = ReadVector3(reader);
transform.localRotation = ReadQuaternion(reader);
transform.localScale = ReadVector3(reader);
}
you're writing a vector2, then trying to read a vector3
I feel like a complete idiot not seeing that.
I'm surprised that function even allowed you to input a vector3 at all...
I have other issues, but I will try to solve them myself. Thank you for your time and I will use AI less from now on when in comes to coding
Theres an implicit conversion from vector3 to vector2, so not the functions fault
Spent the last six hours banging my head against a wall trying to figure out why the Continue Button in Dialogue System isn't working and why my responses keep collapsing down and playing at the same time as the rest of the dialogue. If anyone has any insights, please let me know.
Doesn't sound like a question for advanced channel, but the answer is: debug.
I’m having an issue with Firebase Realtime Database. When I build the project for PC, everything works perfectly: data is sent to the server and received correctly. However, when I try to build it for Android, it doesn’t work and stops at the stage of requesting the JSON file. How can this problem be solved, and has anyone else encountered this?
soo unity added build profiles soo can I use them for building the game via C# code? like ```cs
public static void BuildClient()
{
BuildProfile.SetActiveBuildProfile(ClientProfile);
// what else?
}
like if its possible to via code build current build profile for CI needs
nvm I found ```cs
BuildPipeline.BuildPlayer(new BuildPlayerWithProfileOptions()
{
buildProfile = ClientProfile,
});
how can I detect and categorize mouse flicks into 3 different types?
Something like:
if mouseFlick1:
normalJump
else if mouseFlick2:
higherJump
else if mouseFlick3:
highestJump
Where mouseFlick1 would be like a quick and short flick of the mouse, etc.
mouseFlick2 would be a longer flick of the mouse
I don't think that's an advanced question.
You can implement the logic of deciding what flick it is in your input manager class. Then pass an enum or something to whoever needs that input, like your character controller.
You can implement the logic of deciding what flick it is in your input manager class.
Yeah but how?
if I just track previous mouse position and calculate the delta by using current mouse position and previous mouse position, it'll be shit
Wdym by "it'll be shit"?
Is this in terms of detection or holding data?
For detection, start position - end position / time Or just use the mouse velocity.
The detection should probably be something like:
- wait until mouse is not moving much.
- then wait until the mouse velocity exceeds a certain threshold, marking the start of the flick.
- wait until the mouse stops again.
- use the duration between the start and stop of the flick and the overall distance travelled to determine the category of the flick.
Hey guys, I'm a bit confused with the wording in Unity's documentation and my own understanding of the GPU. There is a function Graphics.WaitOnAsyncGraphicsFence which I assume waits for a graphics fence in the GPU’s command queue/buffer. This fence should be a point in the GPU’s queue, so when I call the function, the CPU should be stalling while the GPU completes all tasks on its queue up until the fence at which point the CPU will resume. This is what I think should be happening, but the documentation clearly states This method returns immediately on the CPU. Only GPU processing is affected by the graphics fence. This doesn’t make any sense to me, is my understanding wrong?
https://docs.unity3d.com/ScriptReference/Graphics.WaitOnAsyncGraphicsFence.html
I'd assume that it's basically putting a fence command in the queue, so the wait is happening on the GPU, rather than CPU. Any commands you'll dispatch after that would be executed after the fence was resolved.
The key here is the fact that the GPU may have several queues running in parallel. Usually a graphics and compute queue.
This fence is for syncing between these queues.
So if it's a compute shader fence the GPU compute queue is stopped immediately(? or is it when the command is read) while the CPU resolves the fence meanwhile the GPU is processing the graphics queue until the CPU reactivates the compute queue? Is that correct?
When the queue reaches the fence command, it would stall untill the fence is resolved.
The CPU has nothing to do with that at this point.
Ok thanks! I guess this makes sense with multiple queues
GPUs have something like a command processor that processes the queue/s. It also manages the fences and stuff I think.
Oh so what you're saying is that the fence exists on both of the queues, when it's hit in either it will wait until the queue we're interested in(say compute queue) hits the fence at which all queues will resume processing. So it has absolutely nothing to do with the CPU
No. I'm not saying that. The details of the implementation would depend on the graphics API and the hardware.
I don't know if the fence exists on both queues or there's some more sophisticated mechanism, but the point is that the GPU both checks and satisfies the condition of the fence, so yeah, CPU is unrelated here.
Though, again, it might be different depending on the implementation and there are also other types of fences that actually sync with CPU.
Actually, it seems like the async fence is just one type of fences in unity:
CreateAsyncGraphicsFence Shortcut for calling Graphics.CreateGraphicsFence with GraphicsFenceType.AsyncQueueSynchronisation as the first parameter.
And if you look at the types enum, there seems to be a CPU fence as well, though it seems to not be supported ATM:
https://docs.unity3d.com/ScriptReference/Rendering.GraphicsFenceType.html
Wait here's my understanding right now
That way we can guarantee that all commands administered in any buffer after the fence must have command 1, 2, & 3 completed in buffer 1
Yes sort of. I'm not sure if it's put in all the command queues or not. And how it is satisfied either, but I think the purpose of it is illustrated correctly.
Also, there's a difference between command queues and buffers. Command queues are usually implemented as physical microchips on the GPU, so there's a predetermined amount and purpose. I think modern GPUs have graphics, compute and copy queues.
Command buffers on the other hand are lists of commands that you send to these queues.
So there is probably another layer of abstraction between the two concepts I see. This is starting to make sense tysm.
Yes, there's a lot of abstraction. At the lowest level you have hardware implementation that no one sees aside from the producers of the hardware, then there's the driver, that usually implements the graphics APIs, like d3d12, and abstracts the hardware implementation. On top of that you have the engine that abstracts all the different graphics APIs. And then we only have a subset of API that the engine exposes to us.
I guess the only way this hurts performance is if the command queues are tied to work load distribution on the GPU so having fewer queues issuing commands would cause a less optimal working conditions
That or all the command queues run dry and the fence takes a while to resolve
The fence you mean?
Yeah
Yes, typically you should avoid using fences unless absolutely necessary. That's basically stalling the GPU. You shouldn't need to mess with them, unless you're implementing your own pass or render pipeline imho.
Hello. Does anyone have some tip on how to go about debugging seemingly random native crashes / memory bugs in il2cpp builds? It happens all over the place in Unity engine code (memory allocator functions, gameobjects enable / disable, ...) but I'm assuming there must be a common cause (?) for them. I can't reproduce reliably and I'm not sure where to start.
If your project is dividable, you can remove some parts of it, build it and profile it to see if removing some parts fixed some issues. If you test things one by one, then you're able to narrow the problems down. It's time-consuming though, because you need to test multiple versions of your project and each test might take some time (since some issues might happen periodically).
Thanks. I definitely plan on doing that but the issue is so rare I feel like it would take forever. I'm trying to find a way to reproduce it more consistently first.
Is it possible to get this kind of crash (Memory access violation & such) because of a bug in "regular" safe scripting C# code, or does it necessarily have to be cause by unsafe C# code and/or native code (.dll plugins, il2cpp/unity itself, ...)?
In terms of "safe" methods, I'm not sure about memory access violations, but memory leaks and garbage generation can happen if you write the code without knowing how to avoid those. It's worth mentioning that sometimes there are bugs inside of the plugins that can be added to the project (what I mean, sometimes people create assets that don't have the highest quality). Sometimes you may generate issues if you're using things wrong.
The more essential some plugins are, the less likely they are to contain some stupid bugs, because more people are using them and more people are reporting feedback and/or solutions to the creators of those plugins. But keep in mind that fixing issues takes time and some issues happen in rare circumstances (e.g. one plugin could cause a memory leak, but only if you had a gamepad with a gyroscope connected).
Try playing and reproducing the crash with the debugger attached. It should break at where the error is thrown.
Technically, you don't have C# in an il2cpp build, since it's compiled into C++. So all of your code is susceptible to access violation.
there's various errors (like null ref exceptions and index out of bounds errors) that cause a crash on il2cpp rather than logging an exception - there's options to turn the checks on which could help for debugging but i think they're off by default these days: https://docs.unity3d.com/6000.0/Documentation/Manual/IL2CPP.html#EnablingRuntimeChecksUsingIl2CppSetOption
i feel like there used to be somewhere to enable them globally in the player settings but i can't find it in unity 6, i think setting it in code before a build via EditorUserBuildSettings.explicitNullChecks and friends should still work
Yeah but I'm pretty sure by the time the error occurs some sort of memory corruption has already happened and that's what I would need to catch. Since the stacktrace for the crash is always different. I've had memory access violations in UnityPlayer.dll!Monobhaviour::RemoveNodesFromLists(), UnityPlayer.dll!block_remove(), UnityPlayer.dll!mecanim::TransformValueArrayCopy(), UnityPlayer.dll!GetComponentsImplementationRecurse(), UnityPlayer.dll!MonoBahaviour::vector deleting destructor(), ...
Well, You might be able to see where it's coming from at least.
I really doubt it's actual memory corruption.
Though, if it is, there's a big chance that the cause is somewhere in the stack trace.
Anyways, with a debugger attached you might be able to gather enough info to guess what the cause is.
I'll try that, thanks. I have ~15 crash dumps with stacktraces that have nothing in common (except for the fact that they are invalid memory access) which is why I suspect some form of memory corruption that blows up at some later time.
Can you share some of the stack traces?
(Sorry I hope dumping screenshots like that isn't considered spamming)
What version of unity are you using?
2022.3.19f. I know it's not the latest patch version I was planning on trying to update in case that was i Unity bug. Although I didn't find anything explicitly mention in the release notes that look like that could be a fix for that.
I'd recommend updating to the last minor version
Can you see at what point the faulty address originates? For example in the first screenshot?
Thanks for the link. I have a few places that do that (System.Reflection.MethodBase.Invoke(null, object[])). I'll try purposefully invoking these parts of my code more often to see if I can get a more reliable reproduction (to confirm that it's gone when updating).
It sounds like a pretty dangerous api to use
Really? I use for typing commands in a developer console.
Yeah. Especially in an il2cpp
I've always assumed that code stripping issues aside il2cpp fully supports reflection.
Though that's just my opinion. Never actually used it. I prefer to stay away from reflection.
The dotnet/C# reflection is very different from what you get in C++
I wouldn't be surprised if there are cases where the conversion is not implemented ideally
There are also some restrictions of reflection on IL2CPP:
https://docs.unity3d.com/Manual/ScriptingRestrictions.html
~~Also agree, it's (probably) a case of "Too Good To Be True" with reflection in IL2CPP. Almost noone uses it so you're probably just encountering undocumented bugs. ~~ ignore
Unity wants Reflection to work in IL2CPP, as much as the target platform will allow for. If there are crashes or instability, that's a bug that they will want to fix or document as incompatible if they cannot fix it.
I use Reflection heavily in a shipped IL2CPP game, including generic method instantiation and invoke.
Interesting, good to know. What Unity version?
I've been using it across 2019.x to 2021.3 LTS.
yeah, reflection is pretty reliable on IL2CPP with the caveat that it'll explode if you try to emit new code or touch something that was stripped out 😅
of course you can use the Preserve attribute to prevent stripping if you need to
very handy for dynamic generics
Coming from UnrealEngine we have CastChecked which is a cast that will assert that you casted correctly. It is used when you are 300% sure that the cast should succeed and it's mostly a macro.
In Unity, I made my GetComponentChecked but I am not sure if I can inline this or make it more macro-like 🤔
public static T GetComponentChecked<T>(this MonoBehaviour monoBehaviour) where T : Component
{
bool success = monoBehaviour.TryGetComponent(out T component);
Assert.IsTrue(success, $"Component {typeof(T)} not found on {monoBehaviour.name}");
return component;
}
any opinions/ideas? 🤔
I honestly dont see the point of that above TryGetComponent
You can put [MethodImpl(MethodImplOptions.AggressiveInlining)] to inline methods, if the compiler/JIT is not already doing it for you.
Interesting, I assumed that was pretty much what assert was doing
It's a short way of doing
bool success = TryGetComponent<SomethingThatMustBeHere>()
if (!success) crash();
this is for unrecoverable things. if that something wasn't there it is a human error and must be reported ASAP to the programmer 😛
but it's not short is it?
also things like this should come out in testing
bool success = TryGetComponent<SomethingThatMustBeHere>(out var thingy);
if (!success){
crash();
}
thingy.doStuff();
vs
var thingy = GetComponentChecked<SomethingThatMustBeHere>();
thingy.doStuff();
I am saving one if statement, yes 😛
well, yes if you totally ignore the other 4 lines of code you wrote to do it
Huh? They only have to write the method once, everything that uses it is now saving lines of code. Do you know what a method is?
It will be inlined, so the compiled output will be as if they wrote it out manually at each call site, without needing to do so.
don't try to be clever. It's still getting executed though isn't it
We're talking about saving developer time.
and readability 🤷♀️
great, if you are happy to sacrifice runtime for developer time , you carry on
And, as I said, that is why we test. If someting as critical as a missing component is not thrown up during your testing you are doing something wrong
The assert will be stripped from the final build and the method is inlined. The compiled result will be exactly the same as if they were using TryGetComponent directly. As far as I'm aware, there is no performance penalty with TryGetComponent compared to GetComponent at runtime, it's actually faster in the editor.
That's what the assert is for! For throwing during testing.
why do you need the asset? A Null ref is just as good
In my brain, Assert means "This should never happen, it's not something you can catch and fix, it's fundamentally wrong with your code" while exception means "something went wrong, catch the error and recover somehow" 🤔
I dont see it, an Assert or a Null Ref both mean 'I fucked up'
The return value may not be used directly and maybe just stored into a field, where a null value is technically valid, but at that specific call site, a non-null value is expected.
you will crash very far from the faulty GetComponent
Now, if you wrote your own TryGetComponent in a namespace you could replace at build time, then I might see the logic of what you are doing
I don't see why that would make any difference 🤔
because then you pay no additional overhead in a production build
I don't see how this will have any overhead when the assert call is stripped. Do you disagree with what I said here? #archived-code-advanced message
Potential overhead is a valid concern, but that's why they came here asking if they can inline it like the Unreal macro.
Aggresive inlining can actually detrimentally affect performance
Sure. Do you think that is the case here?
yes, because of the generic
it just seems such a pointless thing to do to save a programmer writing a line of code.
The way I look at it, I write code once, that code may be run a million times a day if not more, so it is up to me not to pass overhead on if I don't have to
I don't think aggresive inlining will often (ever?) decrease performance. The compiler can still chose to not inline the function if it doesn't think it makes sense. I think Unity uses it all over the place internally.
It does make debugging harder.
MS Docs would disagree with you
I personally have never seen a performance benefit from aggressive inlining worth a damn
I use it on small functions that get called 10000+ times per frame and it help a lot
ok, but if I had code that needed calling 10,000+ times per frame the word 'Refactor' would spring to my lips
10,000 doesn't even seem that much to me for a hot path.
Yeah that's like the minimum
Stuff like this
Or this
So you're concerned about performance and yet you declare a property to save you typing 16 characters
I suspect that in the case of IL2Cpp, a getter property like that would get inlined even without the attribute.
And I mean, if the abstraction is costless at runtime, I don't see why not.
yeah, don't even use Physics.defaultContactOffset, just find out the default value and hardcode the 0.01f everywhere in your code 🙃 🙃
I am just way too old school for shit like this
As I said Unity uses it extensively. I can see the method call go away in the profiler and for very frequently called functions it saves a non-negligible amount of time per frame.
Virtual function calls are even more horrible. I don't know how smart il2cpp is at devirtualization in specific cases but I inline them anyway (and I seal my classes everywhere I can).
you will never win an argument by holding Unity devs up as beacons of how to develop anything, let alone C#
Inlining does indeed provide a performance boost, however the performance boost is negligable in the context of almost every code you are writing.
Also, inlining is not a magical thing, it increase the size of code. Not doing it correctly can cause issues.
Yeah I only use it after a function call lights up in the profiler, or for one-liners that would have been a macro if it were C. I don't think it's bad. It's certainly shave a few ms in total of frame time in my game for some heavy computations.
A few ms ? What are you doing...
also, since you mention old school, keep in mind that cpp inline it's (probably?) not the same as the inline that C# might do 🤔
ref: https://landelare.github.io/2023/09/08/inline-does-not-inline.html
I am aware, funnily I dont mind inline in cpp
Thankfully Unity has inlined it so it almost entirely goes away in a release build
Do you use Deep profile ?
Yes
Obviously, that might impact performance... given that it adds additional instruction for each method.
Try to use stopwatch instead.
With a simple for loop.
Pretty sure the difference is going to be less then a few ms.
Yeah but I've got 16ms to do everything that needs to happen in a frame so I'll take the gain from inlining these small methods no matter how small.
We are talking about ns difference if I am right.
In your case, sure do it. There is no reason apparent to not do it. But it will mostly not matter.
looks like it's being called 200k times per frame though!
That would be mostly the issue, but even at that amount I would supprise that it goes to even a fraction of a ms
Yeah I know. I'm doing some stuff over many GameObjects and I should have tired out for this project ECS I think.
Or use better code ?
Pretty sure you could reduce the logic, stagger the logic or even use threading where it make sense.
I mean with 1000s of entities even just having an update method amounts to a decent amount of time.
If the idea is to have 1000s entities, obviously DataOriented Approach are better. But having 200k calls to this particular function each frame seem not necessary
Do you really need to update the logic of each entities each frame ?
That's a bit of an extreme case, pathfinding code with many entities over a very large grid. I just wanted to show that inlining can very much matter for very frequently called methods.
As I stated, your experiment is not particularly interesting given your method of profiling.
you miss the point, if you need to inline to get the performance benefit then 99.9% of the time you are doing something wrong. You should not use optimization techniques to cover up or mask bad coding/'design
Alright, well, I think I can live with doing something wrong like Unity's actual C# code.
you won't get an argument from me on that, in general Unity's C# code is crap
You're right though, deep profiling does increase the cost of method calls a lot.
If you look at the history of Unity, they took a bunch of Mac C++ programmers, threw a C# manual at them and said we want a system, now. So what do you expect?
You have to admit though, Burst is pretty impressive!
none of the people complaining about unity would be able to do a better job or would even be able to specify a provably better system that has the same kind of impact on the ability of people to make their games. Not even Unity itself would be able to do that. It is what it is, a monument to serendipity. It would never have taken off had anyone cared about anticipating problems 20 years down the road.
This
Very easy to complain
Not so easy to do it
anyone know how beamng type softbody works for moving an object?, is force applied to every node in mesh then in every timestep the nodes move and then resolve the change in distances of springs or is every node moved uniformly?
This seems like a heated debate already but I just wanted to say it wouldn't necessarily increase the size of compiled code if it's short enough as commands to shift the stack frame and parameters might be avoided if inlined.
Ok I'll shut up
so i tried this to render my meshes:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnRenderObject.html
but its really glitchy and flickers a lot so i ended up just using Graphics API in an Update function with [ExecuteAlways] and that works fine... so what exactly is this OnRenderObject for because it does not run as often as Update so the visuals don't look right
Hello, Im not sure if this is the right place to ask.
Why when i check "BakeAxisConversion" in fbx import setting, the model gets flipped 180deg? isn't baking supposed to keep it the same and just "bake" ???
#🔀┃art-asset-workflow next time but idk what else you were expecting from the conversion
Sometimes different formats or 3d softwares have flipped x and y, but sometimes y and z are flipped in the case of blender.
yea, but isn't supposed that the model stays in same direction ? when i add it to scene without baking its rotation is (0,0,0) and its looking at z+, when i tick on baking, its rotation is (0,0,0) but its looking at z-
isn't supposed for "without bake" to at least have a rotation of (0,180,0) to mimic baking ?
The children may have a rotation
Or the rotation conversion is ignored by default. Can’t say I’m an expert
Can I prevent unity from serializing the default values? or at least automagically serializing them?
My use case:
[SerializeField] int a = 4;
once unity editor sees this, it writes a 4 in a yaml file forever.
i later change the default to
[SerializeField] int a = 6;
Unity hardcoded yamls still say 4. they do not tell me if they say 4 because I wrote 4 or because unity thought I wanted a 4. There is no "reset field" thingy, nothing 😬
I want a [SerializeIfNotDefault] kinda thingy
Maybe some editor script in reset? or something am I missing? 🥲
My current hack: Rename the variable. Unity yaml doesn't know the field, now it hardcodes the new default and result achieved... but this is a very ugly hack since I lose ALL serialized values for that field, not only the default ones
does anyone here have any idea how to make a voice recognision keyword system compatible with photon voicechat?
If you want your variable value to be set from the code and not from the editor, don't serialize it in the first place.
also there is absolutely a reset for your scripts. Press the ... at the top right of any component in the inspector and you can reset it there.
You can also write void Reset() { } to change the behavior of the reset
that nukes the whole yaml, not just a field 😅
also... what happens if I manually nuke a field in the yaml 👀
what does "nuke" mean
delete 😅
effectively resetting a single field 🤔
That will give you the behavior you want, but obviously you have to do that by hand.
sure
the closest solution I can think of right now is a 3 fields solution
- serialized value
- serialized flag: use serialized value
- constant default value
🤔
by default the flag serializes to false, the constant comes from the code, the serialized value doesn't matter too much if the flag is set to true 🤔
I agree though, this would be a nice-to-have. This behavior of default values getting serialized is something that a lot of beginners get confused by. It makes sense when you know how it works, but it's still not friendly behavior.
I can totally encapsulate this behaviour on a class/struct with a custom drawer 👀
I can fix this!
Thanks both of you ❤️
I was going to suggest this, though I'm not sure what the best way to store the default value is. It can't be stored as an instance field in the serialized class/struct, because Unity will replace it with its own instance. I guess it could be an attribute, but that will require Reflection to read from and can only be basic primitive types.
there is NonSerialized . I can still show it in inspector with reflection black magic 🤔
Maybe I'm wrong, but I think Unity will completely replace the class/struct instance with its own from the serialized data, overwriting whatever default value you may be passing through the constructor. But maybe they are just overwriting the instance created by the script, in which case that can work.
ohhh, I see what you mean 🤔
I will experiment 👀
There are ways to hide them but they’ll likely still be serialized.
You can hook up custom inspectors with conditions to hide them in the inspector
Not sure if that is what you wanted lol
basically, I want unreal's yellow arrow 😛
I know how unreal does it, it's messy and I... am not smart enough to recreate it in unity 😛
but I can try to hack something together 👀
@azure meadow what's the effective difference between the default value coming from the default init or from user input?
Seems the same from the point of user experience.
if I change the script default value, the default value in the editor is not updated
my use case: I had a default easing in the behaviour that tweens all my popups.
I changed the default easing in the code... nothing happened in the game because unity stored a copy of my old default value 😅
if Unity instead of storing a copy of my default value stored something like dunno, ask the script then it would have refreshed my code value.
and I have lot's of popups 😅
Again, my workarround was to make the variable animationEaseIn2 so there is no known serialized value by unity...
I know I never made any override for that field in any of the popups... but if I had, I would lose that override 😅
For funzies: Unreal does this by having a "Default Object". Something like a static instance that nobody can write but everyone can read. Most things compare themselves with their own Default Object.
(the CDO does more things, but one of those is the default values 😛 )
HEre's the thing:
- You're used to working with a different program that has a different workflow
- You want Unity to work the way you're used to
- Unity works differently
- If Unity's default behavior changes, Unity's existing userbase flips the Monopoly board.
I know 😅
I am not asking Unity (as a product, as a company) to cater to me
but I will do my best to bend Unity (as my local tool, my project) to work in a way that is confy to me 😛
and I know I am bending the hell out of it, and it might break in my face 😛
Couldnt you just implement something similar to what unity does with that default object? It seems not complicated
Honestly I come across this like once a month and just do some hardcoded logic in OnValidate which seems to work
I still try to manage multi-tile terrain in runtime but when I try to smooth the terrain the connection gets broken 😦
Any advice?
Perhaps this is not advanced, but how do you go about making a character controller slide/fall down a wall which is too steep? The only way I can think to do it is check multiple points below the character with rays, but that seems expensive.
You should have access to the ground normal in your movement code.
And while we're at that, the solution would depend heavily on how you have the movement implemented.
How do I access the ground normal?
Also, not advanced. I'd even say #💻┃code-beginner
Depends on how you're moving your character and handling the grounded logic.
Do you not have any jumping logic?
I do, yes, but its done through move. I'm currently figuring out how I want to handle it since I discovered that the character controller doesn't work with sloped ceilings if you move with the entire vector 3 all at once
How are you preventing your character from jumping infinitely?
isGrounded
I check if I'm grounded before moving, and after, and then use that to determine if there's slopes etc.
I dont use isGrounded directly in scripts to check if I'm on the ground, only in the collisions script itself. Since sometimes I need to set it to 0 manually when jumping, etc. So I use my own variable for that.
I see. You'll need to use a raycast if you want access to the ground normal then.
That's what I figured, but it seems a but expensive since I'd need to do more than one.
However I have no frame of reference for how expensive 4 casts or so are
It's not expensive. Are you planning to do thousands of them per frame?
nope, but on all entities which use the collision script
The best way to figure that out is to try it. Test and profile
Which includes enemies.
But I can tell you right away, that you should probably worry about performance only when you have a working prototype.
There's no point in optimizing a game that doesn't work as intended.
True, but I've worked on enough 2d games to dread editing collision code later, since chances are a bunch of stuff breaks.
That's part of development. Use version control if you're afraid to make breaking changes.
Hey,
Anyone knows how I can calculate the vector to represent bending direction on a rod ? I know it is a vague question but I don't even know how to explain that 😄
I made a blend tree for the rod bending and I want to calculate direction x and y based on the rod and bait.
Assuming the rod and bait are gameObjects, bait position - rod position.
Tip of the rod or base ?
Depends on what direction you need.
I've checked with the tip but no chance. I should check with the base too.
Direction = target position - origin position.
I don't know what you mean by "no chance". You should've got the direction from the tip to the bait.
Hmm, It is totally different to direction I guess. Because how rod bends to different directions is totally different than a gameObject. Also how much it is bent is different too.
I think rod forward direction is important too.
does anyone here have any idea how to make a voice recognision keyword that does something ingame with photonvoice? im a new coder but im looking for help because the more i get helped the more i can learn
photon voice would be for communicating with other players AFAIK - i.e. online voice chat.
Phrase recognition would be a separate thing entirely. If you google Unity phrase recognition you'll get a bunch of results.
thanks
should i worry about using dictionary too often on my manager classes will it lead to memory fragmentation or c# is smart enough to clean things up?
depends how you use the dictionaries
i always use them on my manager classes to keep track of the objects, for example items created by players (multiplayer game) so sometimes there is a lot of adding or removing depending on the player playstyle. when dictionaries start to cause memory fragmentation?
i always thought it was a good practice to use dictionaries but today i realized the memory fragmentation is a thing
then you want to think about using the size option of the constructor
by the way its a unity bug. import a model, and click on bakeAxisConversion and apply multiple times, and sometimes it flips and sometimes it doesn't
so as long as i don't exceed that size on the constructor memory fragmentation is not likely to occur?
is it somewhat caching the slots beforehand
exactly, but be aware, if you do exceed that number of entries doubled will be allocated leading to possible memory waste. So it's a fine line to walk
oh so its allocating in batches if i exceed
Oh neat.
yes and it doubles the number of entries every time it allocates. I like to start the size at about 25% of my expected max size
thank you, glad i don't have to change practices i love using dictionaries
Sorry for misleading you then lol
Pretty sure you'll end up with memory fragmentation regardless as you allocate and free things.
it also has a capacity which doens't go down when you remove items (unless you call TrimExcess i think?), so adding and removing items over time shouldn't cause any new allocations unless the size increases again
only when all of the buckets of an allocation are empty. so using the standard 4,8,16,32 etc, yes you will get fragmentation. allocating larger blocks should reduce this even with lots of add/remove
but it is a fine line to walk
Meant as in a Unity app in general. But yes, reducing excessive churn when using collections would reduce it
ah, yes, very true
and, that's a good point, having large allocation blocks for Dictionarys and Lists can adversely affect the effectiveness of the GC when it tries to find space for the allocation. Yet another thing to consider
Sometimes I even miss C++ just a bit
if you actually are in danger of running out of usable memory due to fragmentation on your target devices, it's often better to look at other more old fashioned approaches like preallocating any large memory blocks you need early
usually a few dictionaries are not going to be the problem 😛
Absolutely, good advice
yea tbh i wasn't even aware until today and the way i discovered it was the gpt advise, so i don't even know how memory fragmentation looks like in action or how does it affect performance
Do some reasearch into how the GC allocates and deallocates memory blocks, it's quite shocking
it's mostly a problem with large allocations like loading textures, if there's no space large enough to allocate one it'll just crash since it's effectively out of memory
can you advise any good source that i can look into i would love to learn
understood so its not gonna hurt my game since each allocation is not more than a few bytes
thanks everyone again
note that unity uses the boehm GC though which is not the world's fanciest garbage collector lol, it's lacking in a lot of areas compared to the state of the art .NET ones
memory fragmentation is not something you normally have to worry about in C#!
True in a 'normal' c# app. In Unity, with the way it works, not so much
i mean yeah it's fine for Unity, you definitely shouldn't be allocating industrial levels of garbage like .NET is designed to handle anyway!
trouble is you have no control over it, Scenes being loaded, Game Objets being destroyed, Materials and Textures being Loaded and Unloaded etc, etc
Some Unity specifics (including changes in 2019.1) https://medium.com/my-games-company/memory-mastery-comparing-unity-and-net-garbage-collection-4c23e693d3a5 compared to .NET
Hey,
Anyone knows what is the equation to convert rod bending based on the rod direction and bait position to blend tree ?
It is how blend tree looks like.
First of all it's not a an advanced question. And second, didn't we go over it yesterday? A direction is target position - origin position.
blend tree is just fed with 2 floats, in your code you can subtract the bait position from the rod position to get a vector normalize that use it to set the too floats that feed the blend tree
Does anyone know what the best way to go about saving an chunk generation to a custom json or binary file for a saving and loading system? I want to see others point of view on how they would go about saving the chunks.
https://pastecode.io/s/0807f71r
This above is how my chunks are generated
Save the seeds used for generating the chunk and delta of any changes the player has made to the chunk.
Hey folks, is anyone aware of a way to batch convert a bunch of prefabs to be variants of another? I couldnt find any such tooling, and went down a rabbit hole of writing a tool to do it, but hit a dead end. I got everything working, with the exception of losing references to the when overwriting the original with PrefabUtility.SaveAsPrefabAsset()
Could you explain why you think you gave me a right answer ?
Yup, I know it is just 2 floats but does it mean any vectors could be use in that blend tree to give a right answer ? (btw, I've tested what you suggested but it doesn't work)
So rod can bend to any direction though its base doesn't rotate at all because it is in the hand of the character, so bending happens just at the top part. Also rod direction is changed by the character to left or right and up and down and it could give a different values to the blend tree just by moving up and down (Also how much it can be bent)
The values shown in your video above are the unit circle (rounded) so having a normalized direction makes sense here, as both people above suggested to do. It's not really clear what you want otherwise because all you've said you have is the rod and bait objects. And what do you mean "any vector"? What other vector could you possibly be calculating here
I tried to assume it is in 2D from top down angle.
Then I thought I can find the right direction by this:
Vector2 projectedRodForward = new Vector2(_context.rod.transform.up.x, _context.rod.transform.up.z).normalized;
Vector3 lineDirection = _baitHandler.transform.position - _context.rodBase.position;
Vector2 projectedLine = new Vector2(lineDirection.x, lineDirection.z).normalized;
float angleSign = Mathf.Sign((projectedRodForward.x * projectedLine.y) - (projectedRodForward.y * projectedLine.x));
float angle = Vector2.Angle(projectedRodForward, projectedLine) * angleSign;
float rad = angle * Mathf.Deg2Rad;
float cos = Mathf.Cos(rad);
float sin = Mathf.Sin(rad);
Vector2 bendDirection = new Vector2(0 * cos - 1 * sin, 0 * sin + 1 * cos).normalized;
It can give me a right bend from top down view as far as I notice but it is not correct in 3D space.
The reason is, rod bending and rotation happen on the top part and base part is always the same. It is hard to show in the video somehow.
I have no clue what this means, or how that relates to why you cant get the direction normally. That math above definitely looks overcomplicated and doesnt really make sense either. If you wanna ignore one axis just set the vector2 to be whatever values you want from the vector3
Here you can find information about math behind unity 2D blend trees: https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf
Chapter 6
I have successfully implemented all blendtree models in Rukhanka animation system, and they are perfectly coincides with Unity's.
What makes you think that I didn't? You didn't provide any feedback either, so I assumed the issue was solved.
.json has no problem saving dictionaries, right?
Depends on the serializer
depends on the json library, test it and find out
i dont use any special library... its self written. i just save values as json. works with normal values. but my dictionary wont show. not sure if its my code or a json problem lol
you wrote your own json library?
no. sorry that was misguiding.
so which library are you using, there are many
How are you saving values as json?
have to let us know which lib you are using, like the Built In JsonUtility does not support it, but most other common ones do
i actually dont know, if I am using one.
so i probably use the build in one yeah. But i found a helper method to convert dictionary to json string in my old code
its a very complete implementation
and this helper method works to some extend. it already saves something, but the values are empty
just use a lib that supports it from the start instead of hacking around it
Don't you think you should know?
I'm sure when you decided to use JsonUtility (if that is what you are using) you went and read the documentation to see what it could and could not serialize
How is it that you don't know what code you're using or what it does?
You should definitely know that. Especially if you're asking in this channel
yeah maybe i should. but i havent touched that code for months lol. and its my first time writing a save system.😓
Then go over the code to refresh your memory of it. It's not very helpful(both for you and us) if you can't answer simple questions about your own code.
no maybe about it. This channel is not called 'Advanced' for nothing
i think, i am indeed not using any library... maybe thats why
\wtf do you think JsonUtility is if not a library?
then what are you using, the built in one JsonUtility?
na nvm. i found it. its JsonUtility
yeah that does not support dictionary
it only supports the same types unity can already support in the inspector
ah ok thanks
the one i linked above is a full featured one
Though you can implement your own serializer for dictionaries specifically and keep on using JsonUtility.
its what 90% of people use for json in unity these days if they need more then JsonUtility
// Take a Dictionary and return JSON string
public static string SaveDictionaryJson<TKey, TValue>(Dictionary<TKey, TValue> dictionary)
{
JsonDictionary jsonDictionary = new JsonDictionary();
foreach (TKey key in dictionary.Keys)
{
jsonDictionary.keyList.Add(JsonUtility.ToJson(key));
jsonDictionary.valueList.Add(JsonUtility.ToJson(dictionary[key]));
}
string saveJson = JsonUtility.ToJson(jsonDictionary);
return saveJson;
}```
is what im using atm
i will take a look at it. thank you
Then I guess we can consider the question solved?
the initially yes. no values show up for the moment, but ill look into it first
So, it doesn't work? Then you'll need to debug it.
yeah would first look into what a JsonDictionary type is and if its defined Serializable
though persnally i would just get json.net and use that
I am having lots of issues trying to self teach myself how to work with binary data. Where is a good area to learn this information as a self taught programmer
Preferably not a paid education somewhere free
what do you mean by "work with binary data"? All data is binary data. What are you trying to do? Create a custom binary serializer / data format?
I am writing a serialization script for UGC content that takes all the vertices, colors, mesh, animations, and other components to a writing script and rewriting them with additional player input added to it. I have refactored my script so many times, that it is nothing alike what I started with which is good since I learned a whole lot. But the real issue is the fact I am still walking blind in this subject, like yesterday I just learned of magic numbers in byte data and how useful they are.
I wish for some kind of guide, or direction to follow. Like I just learned today you need to encrypt a binary read and not a JSON
I recommend taking a look at BinaryWriter and BinaryReader. There is some good example code here:
https://learn.microsoft.com/en-us/dotnet/api/system.io.binarywriter?view=net-8.0#examples
The key is just that your code / format should determine exactly what kind of data is expected in the file and you just call the appropriate Write/ReadXXX method in the right order
for example if you want to write a position, you could write the X, Y, Z float values
to read it back, you call ReadSingle three times.
That is exactly my issue, I keep expanding the amount of data I need to send or what kinds become I have never done this before. So each time I think the scripts are good I have to refactor both my writing and reading script to fit the new needs. Is there any way to make it flexible enough that it can work with or without some of the written bytes? Because right now if one thing like the normals have an issue the entire script reading will have an issue not skipping the single bad one, because the byte data is seemingly read that way.
Typically to have "optional" data in a format you would do something like have an extra byte before the actual data to indicate whether the data is there or not
Or you would have something like an indicator before each part of data that indicates which bit of information is about to come
that's how protobuf works
If you're curios: https://protobuf.dev/programming-guides/encoding/
Explains how Protocol Buffers encodes data to files or to the wire.
One option btw is, instead of writing your own format and your own serializer, you just use an off-the-shelf thing like protobuf or messagepack
I have never heard of these programs, do you recommend them or do you recommend I try to code it myself?
I recommend trying yourself if your format is simple and unlikely to expand that much.
I recommend learning protobuf otherwise
I have used protobuf in my professional life for a long time now, it's very good.
Messagepack is also supposed to be good, but I've never used it
What would you define as simple? Like is vertices, mesh, material data, animations, and other related data for a character. The goal of this script is to take a character a user uploads and I attach the needed components on top of the their artistic design to make it playable
is this too much to ask for protobuf?
Have you considered using Asset Bundles?
I honestly do not know what that is
Thank you for this information, you probably saved me an entire month of beating my head against the wall learning how to code this all in c#
I'm refactoring some use of async void Start() in this codebase, and came across something odd.. when I take all the guts out of it and put it in an async method and forget() it, it breaks horribly. I thought calling an async void method is basically the same as calling an async UniTaskVoid with Forget()? Why does this break?
// old - works
private async void Start()
{
// .. stuff with an await
}
// new - breaks
private void Start()
{
StartAsync().Forget();
}
private async UniTaskVoid StartAsync()
{
// .. same stuff with an await
}
i've never messed with API's before, i'm trying to utilize github's API to get the latest release of a particular repository.
utilizing the string format ($"https://api.github.com/repos/{repo}/releases/latest") inside the web browser does give me a JSON string i could use to fetch the latest release's tag, however, trying to use the same thing in the unity editor using an HTTPClient class returns a 403 error
is there a way to fix this issue? i've never used API's with HTTP client before so idk if i'm missing something
HTTP 403 is the "Forbidden" error: the repository may be private so you cannot see it without being logged in.
the repo i'm trying to see if not private, it's public
which... only confuses me further
even opening a link of the API inside edge where i've never logged into my github account lets me see the JSON metadata
You'll have to show some code
ignore my cave-man usage of Thread.Sleep, the actual production code will use async await/editor coroutines
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
forgot that people here use hastebin, thats the hastebin with my menuitem that's trying to get the latest release of a repo
response.Result triggers the 403 exception
what's the repo
Wait
Try:
var url = $"https://api.github.com/repos/{GitHubRepo}/releases/latest";
Debug.Log(url);```
I just noticed my code is stupid
Guys I'm not checking while(!completed)
nvm, it still throws it.
https://github.com/CyberAgentGameEntertainment/SmartAddresser
This is the repo i'm doing as a test, its a package repo
works for me with cURL:
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.
Requests without a valid
User-Agentheader will be rejected.
https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api?apiVersion=2022-11-28#user-agent-required
that being said - any reason you're using HttpClient and not UnityWebRequest?
ah that's probably why
UnityWebRequest will fix that too I believe
i didnt know about unity web request
i'll try that out
time to read about the web request documentation
Can confirm adding a user agent fixes the problem (online compiler dotnetfiddle.net, HttpClient)
It worked in cURL because it adds a user agent by default
yup, i replaced httpclient by UnityWebREquest.Get(url) and it has returned the json data
thanks guys, very cool 
For reference, implementation with HttpClient: http://dotnetfiddle.net/BNGUsN
It wouldn't let me share the link if the code contained an URL (wtf??), so I encoded the github API URL to base64 to trick it. It requests https://api.github.com/repos/dotnet/runtime/releases/latest.
wouldn't let me share the link if the code contained an URL
Probably to prevent you from giving someone code that downloads a malicious file and executes it
Hm reading the error message that pops up again, it says I need to be logged in
More of a case of "give us your personal data to be able to use all our features"
Ok this is an odd one. I'm fixing some code up and found this line:
[SerializeField] private Canvas canvas;
I tend to make this readonly - my linter likes it that way - but it shouldn't matter, really. However, in this case, it broke this component. There's no references to this member externally, although I'm sure if I looked, there might be something digging through the gameobject and finding all canvas components and turning them on/off.
Would setting this member to readonly somehow cause that to break? Shouldn't there be some sort of error/warning in the log (ie, trying to set a canvas that's readonly)?
Unity won't serialize fields marked as readonly. Are you still seeing it in the inspector?
I didn't look, but it's being managed all through code anyway (the canvas)
It's some sort of component that identifies a canvas location for a tooltip of an object.. but if the object doesn't have a canvas, it just returns null.. but strangely, when I set that prop to readonly, it failed to set it (wherever in the codebase that's happening - i honestly don't know, haven't looked).. I imagine there's something somewhere iterating all GOs in a branch, finding any <Canvas> components, then.. doing something with them? I just don't see what setting that prop to readonly should cause any problems tho
(or if it did, why there wouldn't be any runtime errors when doing something to the GO with the component in question)
So, you're saying there's some third party code doing some kind of Reflection over all the fields of all the scripts in the scene, and that's failing if this particular field is marked as readonly? Setting this field to readonly doesn't have any effect on the Canvas component itself. You can have any number of fields referencing the same Canvas, both readonly and not. The keyword only affects the field and whether a new value can be assigned to it.
I don't know why you'd necessarily expect a runtime error if this is just some third party code you don't know how works or what it's doing.
But the first thing to sticks out to me is that it's just wrong to make a field that is both readonly and [SerializeField], because those are not compatible.
I'm contracting on a project that's got a ridiculously large codebase of components that do goofy things so.. it's just hard to know for sure. But there is a lot of runtime component composition which is likely interacting with readonly in a way that is broken
I always thought [SerializeField] private readonly GameObject myThing was the correct pattern?
oh wait what am I talking about
Why is it marked as [SerializeField] if you say it's all managed from code? How can you be so sure it's not serialized somewhere, if this is a ridiculously large project?
nevermind, it's readonly for private members, not [SerializeField] members
So - there are a lot of components that have serialized fields as some of the artists create the in-game models by composing several components so they don't have to "write code". Some of these things are tied to a binding framework to do relatively simple things like ... setting a game object on/off depending on an internal field
for example
So you'd add this "set active GO binding" to a game object, give it a target (some other GO) and a path (an internal variable on the "reward show chest VM") and then the GO would just be on/off at runtime accordingly
But there's complexity in the layering of canvases, so much of the UI system creates and staples canvases to objects (at runtime) and sets the sort order of it all.. so .. it's really difficult to see what a given object actually should look like (at design/code time) because it's all composed based on data and at runtime
lots of idiomatic use of stuff like this:
private void SetEnabledAllCanvasWithNames(string[] targets, bool enabled)
{
if (targets?.Length == 0) return;
foreach (Canvas canvasItem in Object.FindObjectsOfType<Canvas>())
{
if (!targets.Contains(canvasItem.gameObject.name)) continue;
canvasItem.enabled = enabled;
}
}
which is just .. super hard to debug since you sorta have to have this comprehensive knowledge of everything in order to debug one thing..
is there a c# syntax to declare an event (UnityEvent or just Event) that makes something like this legal:
UnityEvent<int,int> IWantTwoInts;
IWantTwoInts += (onlyOneInt) => {}
🤔
I jnow I could make (onlyOneInt,_) => {} but I wanted to know if I can tell that event that the second parameter might not be there 🤔
you could just use a function that takes two parameters and calls your one-parameter function
which is kinda what you might do in that (onlyOneInt,_) => {} example
but the event itself doesn't care what the callers do with the parameters, if anything.
I guess it's unclear what problem you're hoping to solve here
not sure what you mean
since we are here... is there a real difference between Event/Action and UnityEvent/UnityAction? 🤔
Yes
I am torn between doing as the romans and unity doesn't always do the smart thing 😅
UnityEvent was created so you can assign listeners in the inspector
If you don't have a requirement or desire to assign listeners in the inspector, there's no reason to use UnityEvent
BTW Action is just a specific built-in delegate type.
You can define your own delegate types
for example, a delegate type that doesn't return anything and takes two float parameters, for handling when a value changes, might look like
public delegate void ValueChangedHandler(float oldValue, float newValue);```
Then you could make an event out of that e.g.
public event ValueChangedHandler OnValueChanged;```
And the only thing the event keyword does here, is ensure that OnValueChanged.Invoke() can ONLY happen from the same class that declared it.
I am avoiding OnValueChanged.Invoke() in favor of getting the delegate list and making sure target isn't null 🤔
To try and catch dead objects still suscribed to events 🤔
but I will look into not using Action<> and using a custom delegate instead 🤔
Better to just... sandwich your subscriptions. I.e. make sure you have a RemoveListener for every AddListener.
Or for C# events - a += for every -=
Usually stale subscriptions end up with an error of some kind - which is good enough to alert you to their existence
In unity-world usually a MissingReferenceException
or a "you tried to access this thingy but it was destroyed"
That's what MissingReferenceException is
does it tho? 🤔
the fact that your object ==null doesn't mean that object is null (actuall,y object==null && object is not null is a cool way to distinguish a real null from a unity dead object :P)
I thought a method of a dead object would crash in a more cyptic way 🤔
anyway, I am trying to make something like dotweens "safe mode"
I've lived through C++ destructors and smart pointers, I've seen the battlefields of roblox maids and janitors, I know for a fact developers will forget to remove their listeners 🤦♀️
Yes that's literally what MissingReferenceException is. It's what you get when you try to access a member of a Destroyed UnityEngine Object. Not to be confused with NullReferenceException or UnassignedReferenceException
ohhhhh, you are right, my bad 🤦♀️
But it will only happen if you try to access members implemented by Unity, like gameObject, name, etc. Unity won't know if you access a purely C# defined member on a destroyed MonoBehaviour/ScriptableObject.
Hi there, I have a project in Godot and I am planning to move it to Unity, but I have a problem with current modding support that the engine provides.
- Godot allows me to build .pck files, which later can be loaded in runtime and injected into the filesystem with an option to override files with the same names.
What is the best way to implement something simular in Unity? I saw that we have addressables and we can build bundles, but I could not really find a way to make all dynamically loaded assets to be injected into the filesystem in a way which would allow for files to be overriden. I have also looked into using UGC service + bridge, but it does not seem to be what I want, since I am planning on using Steam Workshop instead, so relying on Unity service for something like this wont cut it.
- I am using GDExtension in Godot in order to compile mods and the game itself from C++ sources with a compact MinGW build, after which I can launch the resulting DLL as a part of the exported game. This allows me and modders to provide sources of both game and mods without any precompiled assemblies, making this system completely transparent since everything gets compiled and packed on the end users machine.
What would be the best thing to use in Unity to achieve something simular? There are some packages that allow for C# compilation with Roslyn, and there is also a possibility for using something like Harmony/BepInEx out of the box, but all of these rely on either partial compilation of target mod or runtime patching, nothing like what I currently have in Godot. Are there any other options besides these?
Assets bundles
I think VRchat has pretty good devlogs about how their stuff works
Anyone know what is causing this issue using Facepunch.Steamworks?
GetFriends seems to keep returning a null list
I am signed into steam and steam friends
that looks like you are looking at friend which has not yet been filled
GetFriends isn't awaitable
I meant in the foreach friend will not be filled until you actually enter the loop
I don't think I understand what you're trying to say
friends gets assigned before the loop
the foreach loop just tries to use the data that GetFriends provided
friends, yes, but it looks like you are looking at friend which at that point in your code is null
but the friend is just an index from friends, implying that the function didn't work correctly
no, friend will not exist until the foreach is executed which it has not yet been
the foreach doesn't correlate to setting friends in any way, that's why I don't understand
read what I am writing, I'm talking about friend not friends
yes but I don't set friend in the loop?
what? Do you not know how foreach works?
what you
you're saying makes no sense because the foreach just cycles through friends
so friend being null comes from the GetFriends function outputting a null list
yes, and creates a local variable, friend, which comes into scope when you are INSIDE the foreach loop
not at that point becuase you have your breakpoint BEFORE the foreach has executed
oh I think we're talking about different things?
are you saying that friend will initially be null because you just entered the function and hasn't been set yet?
yes
thats not the issue
obviously it will be null
my problem is that the list isn't assigning friend
you should be inspecting the var friends on the previous line if you want to see the contents
I am
and that was what the initial screenshot was of
that's why I said, the function doesn't seem to be working properly
why don't you just set a breakpoint inside the foreach and check? It looks like GetFriends returns IEnumerable<Friend>, so the actual code that fetches and enumerates friends might not even have run at that point
exactly, that is what I have been saying
step over the foreach if it hits the if there is a friend which you can then inspect
you said it returns a null list, but apparently actually it's throwing an exception
how about providing: 1) updated screenshot proving friend is not null while inside the foreach 2) the exception you're getting
also the code containing the try catch
it's throwing because it's null
I never said it wasn't null inside the for each
then you haven't proven GetFriends isn't throwing an exception by itself yet and your screenshots so far have been useless
man, this is code advanced, you should know the difference between a null variable and a null list
I didn't say this either, GetFriends doesn't throw an exception but the data it is looking at is null and it even throws an exception when you try to use it. Just look at the screenshots lol
The debugger clearly shows the item it's looking at is null and clearly unusuable as it goes to catch
nothing to see here
no dude, your first screenshot hasn't entered the foreach yet and friends hasn't actually been iterated. Your second screenshot has the same problem. Change code to var friends = SteamFriends.GetFriends().ToList(); to force all items to be iterated immediately and see what happens
I suppose, I guess you'd assume that the code breaks there, could've clarified a bit mb
you said it goes straight to the catch in the foreach, the catch is clearly OUTSIDE the foreach
yes, because firends is null
or GetFriends has thrown an exception because you didn't do some configuration correctly
\no, you said a null list which is totally different
make the code change I said and look at the list with a breakpoint on your Debug.Log(friends). If that breakpoint isn't hit, it has nothing to do with your foreach loop and your next step would be the look at the exception to see what happened
It'll null ref on the ToList
it's throwing "System.NullReferenceException: Object reference not set to an instance of an object
at Steamworks.SteamFriends+<GetFriendsWithFlag>d__27.MoveNext () [0x00077] in <84b726e257b94473ac18ff6d18ba7c47>:0
at System.Collections.Generic.List1[T].AddEnumerable (System.Collections.Generic.IEnumerable1[T] enumerable) [0x00059] in <51fded79cd284d4d911c5949aff4cb21>:0
at System.Collections.Generic.List1[T]..ctor (System.Collections.Generic.IEnumerable1[T] collection) [0x00062] in <51fded79cd284d4d911c5949aff4cb21>:0
at System.Linq.Enumerable.ToList[TSource] (System.Collections.Generic.IEnumerable`1[T] source) [0x00018] in <1f993cbf88314b1baa1e10ca917bdc64>:0
"
with ToList
so you can now rule out the entirety of the foreach loop
So you need to be looking in the SteamWorks docs to see why GetFriends is returning null
but this is not a Unity problem
indirectly it is
what, the fact that a 3rd party has useless docs is a Unity problem how?
I'm just looking for support that I thought unity devs are likely to relate to
are you missing an initialize call or something? i would guess the interface reference is probably null here
why are you so pressed
Internal being a reference to the steam friends interface which needs to be initialized at some point
I'm running the Init code that's suggested by the only thing the docs provide
SteamClient.Init(480);
SteamNetworkingUtils.InitRelayNetworkAccess();
is that your steam app id and did Init throw any exceptions?
its spacewar app id
and no it doesn't
the entire steam framework runs fine, its just the GetFriends
time for more debugging, then. You should print logs from https://wiki.facepunch.com/steamworks/Debugging, and make a call to some SteamClient.IsValid method they mention in the docs
the stupidest reason this could fail is you don't have steam running
are you 100% sure your init isn't throwing, then?
but I've gone through the SteamClient.Init with the debugger + I have other logic after it and it all runs fine
I also added the debug logic from facepunch before the init and nothing comes up
I tested it with my own appid and still the same
it's possible it's just a bad func
there are some things in the dlls I've seen that are bugged
so I honestly wouldn't be surprised
The obvious thing to do here is create a simple Console App which implements these API's, it will be much easier to debug
it worked instantly for me np in a test project
unity
new URP project (2022.3.42f1), slap this script onto a GO in the example scene, worked fine https://pastebin.com/djzNEn3X
if (Instance == null)
Instance = this;
else
Destroy(gameObject);
Dispatch.OnDebugCallback = (type, str, server) =>
{
Console.WriteLine($"[Callback {type} {(server ? "server" : "client")}]");
Console.WriteLine(str);
Console.WriteLine($"");
};
Dispatch.OnException = (e) =>
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
};
try
{
SteamClient.Init(480);
SteamNetworkingUtils.InitRelayNetworkAccess();
}
catch
{
Debug.Log("INIT FAILED");
}
This is all I'm doing
the only way I can replicate your results is if init didn't run
and your valid is returning true?
if init ran, yes
Console.WriteLine in Unity code???
well I didn't think this was a simple fix anyway 🤷♂️
oh true I just pasted his code lmao
I think it is a simple fix, your init isn't running. Prove that it is. Did you disable domain reload?
it seems to be running the callbacks normally anyway
well I'd assume it is since I'm fetching different steam data like my name and avatar with no problems
also my friends list says I'm playing spacewar
I did but even with it on, still the same
did you try turning it off and on again? Both Unity and steam
this looks suspicious tho
restarted both, still the same
wait I might have found it
SteamUser.OnSteamServersConnected never gets called
what's relevant about that? docs say this is a rare event so hopefully you aren't relying on it for something
at this point you should be using a minimal test project instead of flailing around in yours where something has clearly gone wrong
I'm not, just added it for testing now
does anyone know if it's possible to grab a universal object reference (GlobalObjectId.GlobalObjectIdentifierToObjectSlow(...)) in the ISerializationCallbackReceiver.OnAfterDeserialize()callback?
see unity yells at me if I try
UnityException: GlobalObjectIdentifierToObjectSlow is not allowed to be called during serialization, call it from OnEnable instead
I coooould refactor things to use UnityEngine.Object stuff here but I'd prefer not to :c
(but I have a feeling I'm gonna have to)
Is it because the instantiate chain serializes/deserializes in order to resolve references, so the global id isn't yet resolved or something..?
I would guess? that's all on unity's end!
in my case it's an editor lifetime object during assembly reload that I'm receiving the callback in
and the reference I'm deserializing is an asset reference
so I was hoping assets vs scene objects would live in separate worlds enough for this
Is it important that you get the id immediately in that method? Because if not, you could delay it for processing later, either by adding to a concurrent queue or maybe using EditorApplication.delayCall.
hmmmmmmmm that seems really risky to leave it for one frame
I really don't like getting into DelayCall stuff
Hey guys, I'm asking because I'm pretty bad at math. I have a 3D grid/map with a variety of densities located at regular positions. If one were to envision this grid as voxels, the main difference is that these entries are located at the corners of these voxels. Hence the density at any position can be determined by a trilinear interpolation of the 8 closest corners to the position.
I have a ray that intersects this grid. I also have a way of traversing the grid voxels to determine all voxels that can intersect with the ray. Therefore, I can focus on just one voxel; if I know a ray intersects this voxel and the density of any point in the voxel is determined through a trilinear interpolation of the densities situated at the corners of the voxel, it should be possible to determine mathematically the first point along the ray at which the density is a desired value. I tried brute forcing the calculation, but it expanded a lot; this feels like a very simple problem so I'm wondering if there's any existing solution to it.
Hi, there is a way to create a new AppDomain at runtime ?
I have tried but i have an error that say "Synchronization context.."
Im making a plugin system for my game but i can't unload assemblies before reloading them
You could simply express your density equation in function of a position and then sample the equation for a discrete amount of position.
Like ray marching along the ray? I could, but I don't want to if I can solve for it with a direct way
Why ? Computing an equation can be really hard and even impossible in some case.
You are better off optimizing but having good caching system than attempting to find the equation that fits your problem that seem kinda complex.
Well it should be one time solution--if I solve it in terms of the other variables I can implement it for all cases. As long as the calculation isn't too long it should beat out any binary search for the point or smthing.
Start by expressing your equation in term of X, Y, Z
Then divide it by its composant
Then, you should have the equation of your Ray/Line
Do the same
Then you will be able to isolate your density parameter after
I'm not partically good in math, but I believe doing something like that could help you.
d(x,y,z) = 0.5f
d(ray(distance)) = 0.5f
I'm expressing the line as a parametric so I have one unknown variable(t), I'll show you my work for a bilinear interpolation on paper.
To be honest, it is not really the best place to get math help.
You should look into math oriented forum
At least, it is pretty much what we would all do,
Is there a channel here for that?
Not here. We are game developer, not mathematic expert.
We know enough to navigate, but most of us would either use a considerable amount of time to figure the equation or ask on a forum for that.
Sometimes, stackoverflow can give good answer about math question like that.
Also, consider using the approach I suggested, good caching and pre calculation can help a lot.
Also, not sure how you can have 1 unknown and not have solve the equation ?
d(ray(Distance)_x) = Densitity
d(ray(Distance)_y) = Densitity
I did solve it but I have little confidence it really works--
2 unknown, 2 equation.
The only unknown is t, the parametric parameter or distance along the ray
Oh right, I understand now it is a less or equal problem
it eventually reduces down to 0 = Ct^2 + Ct + C where C are constants
Here’s a basic solution for a bilinear case where I assume the corners are 0,0 1,0 0,1 and 1,1 respectively
Yeah, then minimize the parameter
The left hand side is a constant, and the right hand side can be combined into Ct^2 + Ct so I would just need to use quadratic equation(I guess) to solve it? I have no confidence this works really and this is also a simplified version of 3D trilinear
I mean, try it but
Did you look into how dual contouring works, this sounds very similar.
Is that the theory behind Marching cubes? I guess I could construct the triangles and use existing code for line intersects triangle algorithms…
No, it’s a totally different (analytical) approach to finding a surface
it may do more than what you want, it’s distinguishing feature is that it can detect and construct sharp corners.
Regardless, if you find the plane the ray intersects, by any means, you’re basically done.
Oh that sounds interesting. I'm gonna check it out and see if it could work.
In the meantime I did solve the formula for a 3D trilinear blend with the corners situated at (0,0,0) to (1,1,1)--you can transform the ray so that this is the case.
I know this is old but you just saved my life, thank you ❤️
Took a break on working on the Vortex Engine cuz school started back up but now that I have some free time I'm back to working on it. I'm starting to implement animations and player rotation, and ran into a bit of a problem. Animations are all working as intended with is good, and the rotation works well on flat ground, but it messes up the slope physics completely, and when braking sonic turns at a slight angle for some reason. It should be in the video but it's kinda hard to pick out because I haven't added the braking animations yet. (turning off the rotation script makes everything work normally again so it's definitely the rotation script that's the problem). I've been trying to figure out a solution for a bit now but with no luck, so some help in figuring this out would be greatly appreciated.
Here are the relevant scripts for this:
RotationHandler (attached to capsule): https://pastecode.io/s/rv1418xi
MoveAction: https://pastecode.io/s/8092tzsm
PlayerPhysics: https://pastecode.io/s/p2qb2q81
This C# script for Unity manages the rotation of a player character based on movement input. If the player is braking, the rotation is ignored. Otherwise, it calculates the target rotation from the movement vector and smoothly applies it to the player transform, enhancing the gameplay experience.
https://pastebin.com/YgGrHyn6
For anyone interested I finished and tested a generic solution for this problem. The solution hinges off the fact that if a point on the ray is underground, then one of the intersection points between the ray and the voxel containing the point must be underground.
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.
I am working on a visual novel that uses a bunch of short videos, I am wondering how I should go about handling them in the long run. Currently I preload them before the next video comes up but it feels kind of messy and inefficient. I am wondering if I should be preloading the whole chapter instead.
The current setup is very complicated as it's integrated with my own node system and it grabs players from a small pool.
The largest video in the chapter so far is 9480KB but most range in 100-300kbs besides some exceptions.
holy crap i just took a peek here as a joke wth is that
Prerecorded videos are great if you want something that would be difficult to render in real-time (e.g. highly detailed cinematics). In terms of memory of simple cutscenes, I think it would be more efficient to recreate scenes in the runtime, but since you already have videos recorded, It would generate more work.
Asynchronous preloading videos during the gameplay is a good idea. If you don't have memory issues, then you can preload multiple of those. Keep in mind that the more memory you use at a time, the less number of devices will be able to run your app. If videos happen rarely, and you don't have memory issues, then I don't think loading them in the background would be a huge issue.
wdym? It's what it says it is
Trouble is it's 2D (actual frame by frame full screen animation) and cross compatibility is needed (this is just my job)
I currently have manual nodes in my setup in certain places for preloading but it's kind of messy and unintuitive
I think it would be simpler to just load the next video whenever you have free enough space for them. Just use any algorithm to find the closest possible video node, and load video from that's node.
If you want your preloading to have perfect timing, you could automate it by recording your playthrough, setting timestamps for each visited node, figure out how much time you would need for preloading, and then preload each video that fits in this time interval. Upsides:
- it would know that intervals between nodes might vary (which could be important if the gameplay is non-linear)
- it could postpone preloading if the next video is far away
The downsides: - you would need to update timestamps every time gameplay changes (especially if intervals between nodes would decrease)
- you would need to record it multiple times if the gameplay is non-linear
- the time needed for preloading differs depending on the hardware
I had a similar idea with dynamic loading that involved marking down how much RAM the video takes and to compensate for the hardware being used
but idk how consistent that would be
if a video always takes the same amount then i can just mark it down in a scriptable
should I use the videos through addressables or assetdatabase?
AssetDabase is for Editor only.
i meant bundle my bad
my head is fried after a long day of struggling with editor tools
That is your choice. Addressable is a wrapper around AssetBundle
alright thanks
Greetings.
I would please like to ask for advice on how I can a create a system that will simply store a bool, or an int for multiple items.
Basically, I just want to program that will persistently remember 1 variable for multiple objects, like at least 10 different objects.
PlayerPrefs seem a bit, inefficient because that would mean I need to create 10 different keys, and most likely more if more objects are added, so I want to know if there is a better way to do it.
#💻┃code-beginner but the usual way is to store data as files
how would I go about that?
This summarizes the most common ways: https://unity.com/blog/games/persistent-data-how-to-save-your-game-states-and-settings You can google for details for each of them
thank you
you might like to check out my Player Prefs Lite asset (free on the store)
Hello everyone. I have a Free Camera System that moves the camera in any direction, but I need it to move only inside some object. How can I do this? For example, I made this mesh in blender and I want my camera to stay inside without being able to go outside
you need an inside polygon algorithm
https://en.wikipedia.org/wiki/Point_in_polygon
In computational geometry, the point-in-polygon (PIP) problem asks whether a given point in the plane lies inside, outside, or on the boundary of a polygon. It is a special case of point location problems and finds applications in areas that deal with processing geometrical data, such as computer graphics, computer vision, geographic information...
What is the context here? Why you want to do that?
I want camera to move only inside the building
Why not have the building have colliders and move the camera with physics?
I thought that would be a ton easier than any algorithmic approach
maybe you are right
Just make sure to enable interpolation so the camera movement will be smoother. If I remember correctly, in order to use interpolation for the camera, the camera itself cannot be the Rigidbody but instead you must make a parent of the camera to handle the physics. Don't really know why that is but I think that's the way to go
Hey so im having a bit of problems when making a camera script, so i want the camera to be smoothed (lerped) but im having a problem that if the player does a 360 turn around really fast, then instead of following the mouse all the way around the camera just picks a shorter path.
use slerp instead of lerp and clamp it
already tried it, it doesnt work
you mean it has no effect?
Quaternion.Lerp and Quaternion.Slerp always take the shortest path to the target rotation
Should probably manually Mathf.Lerp the X, Y (and Z?) angles of the camera so it doesn't wrap around the shortest path
good idea, i might try that later
Just make sure to keep track of the floats yourself instead of reading from eulerAngles
hey guys , just a general question, can i create something in unity and use it in a react native -expo based environment? like imagine something of AR in unity and use it in the app which is made on react native-expo?
oh sorry i didnt see that channel, can we continue this convo there?
Sure but I don't know much about it, if you google for "integrating unity with react native" there's a lot of resources
oh, like u havent done it in the past? ik docs are great but asking someone who has already done it before might be more productive right
Maybe start with the docs and ask when you run into issues
okay thank you
I have such an Enchanced Touch input system, I disable it in the disable method, but when I run the game for the second time, the still active log is written.
The scne is empty, there is only this script, what could be the reason, am I not closing it properly?
Version : 2022.3.45f1
This does not sound advanced tbh... but anyways, as you are talking about "running the game for the second time", what do you mean by that? Restarting the application, reentering playmode, reloading the scene? But in any case, you are just reloading your script and it will rerun the onenable function and enable it.
I mean reentering the playmode and but EnhancedTouchSupport.enabled still true
well, you are enabling it with OnEnable
Do you mean your "already enabled log" is being fired?
Did you try to disable it within playmode and not relying on OnDisable? So you can switch it on and off in playmode without hitting the play button
What is your go-to, unity friendly, serializable Dicitonary/Map/Hashtable? 🤔
could be anything to anything or string to anything 🤔
I just want some seasoned opinion 😅
There will be some old implementations that use generics but require you to derive your own concrete class to serialize. That's because Unity used to not be able to serialize generic classes, but that's not the case anymore.
Some implementations derive from Dictionary directly, so it can be used in place of it in code that expects this. I've done that before, but I think it's a bit code smelly, because Dictionary isn't really designed to be inherited, despite not being sealed.
So I would go with an implementation that just implements IDictionary<K,V> , uses ISerializationCallbackReceiver to serialize/deserialize key values to a list/array, and is generic.
Do I need a custom drawer? 🤔
probably, right?
Depends on how fancy you want it to be. If you serialize the data as a list of key value pairs, then the default drawer will be usable, but not pretty, and won't warn against duplicate keys.
Riiight, i've kinda done that with a list of a struct with two values (not generic, it was a very adhoc solution 😅 )
hello, i am trying to get distance markers for the gunsight
(example image)
does anyone has already made a code for that already, i have tried making my own and i have searched on ethernet
Maybe try searching on the internet instead
This isn't an advanced coding issue, and that would likely be made using a screenspace canvas (UI).
i did, i havent found anything usefull for 2 days of searching
In my opinion, you should not plan things with feature that has not been developed yet.
Also, I am pretty sure .NET Core is still far.
but in theory yes!
DoTween and other libraries drop a config scriptable object into Resources
Is that loaded during runtime/initialization with Resources.load? 🤔
Is this a """good""" practice? 🤔
I am always reluctant to connect anything by a string 😅
I would guess it's in Resources to avoid being stripped without forcing projects to reference it somewhere in their scenes or prefabs (using the API).
Assets from Resource folders are always present in the build (even if you don't use them). You can also load and unload them manually. Depending on the scenario both perks can be considered pros or cons.
How do I get unity to stop complaining about abstract type serialization? ("The same field name is serialized multiple times in the class or its parent class. This is not supported")
sorry, not abstract type - but new. eg:
public abstract class MyParent : MonoBehaviour
{
protected float SomeDefaultValue;
}
public class MyChild : MyParent
{
protected new float SomeDefaultValue; // unity no likey
}
(edit - parent is a MB)
(I want to be able to see/set the value in the inspector fwiw)
how would it know which variable to show/set in the inspector if they have the same name?
Shouldn't there only ever be one? Since the parent is abstract? I honestly actually don't know how unity does it's magic re: private members
No there's two different fields
since you did new
What's the best pattern here? I don't really care too much if it's a field or property, but just trying to save some copying and pasting between these entity types that have a lot of the same default values (ie, "move time" between hexes which is 1sec for 90% of the units in the game)
oh derp - I should just be using override yeah?
I'm trying to understand why you bothered declaring the field in the child class at all
it's a field
it's already there
and no, you cannot override a field
you just omit it from the child class definition entirely, and it will work
that's the best pattern
oh uh.. and then what, set it in the ctor/init? i guess that's fine
Set it in the inspector
I'm assuming this field is serialized, since you got a serialization error
it won't um.. really be in use in the inspector, but... I'll need to see it
Lemme get specific - I'm looking to have a Rotation Time (for tweening movement around the map) - but there's some effects that slow/speed up a unit, and other units that have slower "base" rotation time
If you don't want to serialize it then you should not make it serialized, and set it in Awake
this really sounds like something I would serialize and set in the inspector but
if you don't want to - that's what Awake is for
I want to be able to pause (the editor in play mode) and see what the current rotation speed is .. but most of the units have the same rotation speed
k.. I can do that
if you want to show a nonserialized field in the inspector that's what a custom editor is for - or something like Odin
or this https://dbrizov.github.io/na-docs/attributes/drawer_attributes/show_non_serialized_field.html (NaughtyAttributes)
Hm.. I evaluated Naughty last year but I can't recall why I didn't go with it
But I've... encountered enough random needs that I probably ought to take a look at odin/na again and just pull the trigger instead of banging my head on a desk about this stuff 🙂
For now I'm just leaving the (now-serialized) field in the parent and setting its value in the child at init time (basically awake)
Hey guys, I'm working on optimizing my android build which uses the new input system. Does anyone have any tips for how to speed up the eventsystem's update method? It's my longest script in my behavior update section. I know I can optimize my graphic raycasters by isolating them based on what elements are touchable in my UI, which I already have done. My canvases seem pretty efficient at this point. I'm using the enhanced touch API
I feel like you're starting from the wrong end. Sort the data by Time Ms instead.
And expand the finish item
ok one sec
what is the finish item?
here's a different frame
A typo. I meant "the topmost item"
ahhh ok
Can you take a screenshot with only the second level of the hierarchy visible as well?
yep
the majority of fixedupdate's time is due to the contactmanagerdiscreteupdate
I can optimize that, I'm not realy concerned about it
There seems to be 4 categories that each take around 10 Ms. I'd start looking at each of them for the most expensive calls.
FinishFrameRendering is because our map artist made a really high fidelity map so I'm testing with high graphics settings on my phone, NetworkEarlyUpdate is a method built into Unity NGO
There are ways to optimize rendering. Might want to look at what you can do there. Anyways, the raycasts seem to be a very small problem considering everything else you have going on. You might be able to optimize it by reducing the number of graphic components with raycast target checked, but it might just give you 1 Ms at most. The issue is that everything else is heavy.
10kb of garbage per frame will chug on mobile, I'd definitely look into that if I was you
it's actually doing really well rn, stable 60-120 FPS on most devices
I guess these are editor screenshots, right?
no they are profiled on the android build and then imported into the editor
Hi there!
I've been trying to reduce our build size for a while now. What I can't understand is why there is such a difference between Total User Assets and Complete Build Size. Does anyone know?
This is our current build report:
Uncompressed usage by category (Percentages based on user generated assets only):
Textures 705.9 mb 50.2%
Meshes 174.1 mb 12.4%
Animations 22.9 mb 1.6%
Sounds 410.3 mb 29.2%
Shaders 45.0 mb 3.2%
Other Assets 16.0 mb 1.1%
Levels 0.0 kb 0.0%
Scripts 259.7 kb 0.0%
Included DLLs 0.0 kb 0.0%
File headers 30.4 mb 2.2%
Total User Assets 1.4 gb 100.0%
Complete build size 2.6 gb```
Are you maybe baking some data into the scenes? Though if that was the case, I'd assume that's it would add up to Levels.🤔
Not that I'm aware of. And yeah, that's why I'm so confused.
The only thing I could imagine has an impact is the Resources folder (we have a lot of audio voice-overs in there that gets dynamically loaded based on localization and scene). The thing is, I would expect that to be included under sounds (otherwise I can't explain why sounds is 410mb)
Yeah, you'd think that Resources assets are included in the user assets.🤔
But it's an easy thing to test. Just remove the Resources folder temporarily.
Building a test as we speak
You can also try opening the APK as a zip file and exploring it's contents.
Or use android studio analyze apk tool
I'll give that a shot as well
This is the result from building without the resources
Uncompressed usage by category (Percentages based on user generated assets only):
Textures 705.9 mb 70.1%
Meshes 174.1 mb 17.3%
Animations 22.9 mb 2.3%
Sounds 18.4 mb 1.8%
Shaders 45.0 mb 4.5%
Other Assets 11.3 mb 1.1%
Levels 0.0 kb 0.0%
Scripts 259.7 kb 0.0%
Included DLLs 0.0 kb 0.0%
File headers 29.8 mb 3.0%
Total User Assets 1007.7 mb 100.0%
Complete build size 1.8 gb```
Sounds are as good as none (as expected). It's interesting how complete build size seemed to shrink about twice as much as total user assets
Almost as if complete build size is simply an uncompressed, larger variant of total user assets?
I don't think the engine itself takes 800mb, could it?
Nah. I've seen builds of less than 100mb. Also, it shouldn't have shrunk as much without resources if that were the case
The difference seems to be the same. 800 mb.
Oh wait, it was 1.2 GB before
Maybe that's the uncompressed size?🤔
Yeah perhaps. Total user shrank by 400mb, complete shrank by 800mb
Then again, if total user is compressed, why is the apk itself only 600mb
The APK itself is 600?
Yeah with the latest build (the one without resources)
Is there an package extension file next to the APK?
Nope, no extension file
Some extra information: This is the build with resources folder
Hi!
When using Animator.Play(string stateName, ...), the animations work in the editor, but not in the build.
I've also tried Animator.Play(int stateNameHash, ...) in conjunction with Animator.StringToHash(string name)
See:
https://docs.unity3d.com/ScriptReference/Animator.Play.html
https://docs.unity3d.com/ScriptReference/Animator.StringToHash.html
The problem persists whether the strings passed to the methods are hardcoded or interpreted at runtime.
I've inherited this work-in-progress project from an old dev team that is no longer here.
Realistically, refactoring the controller to use state transitions isn't possible.
I need to be able to call the states to be played directly in the code.
Thanks in advance for a solution!
unless you add more context, we can only guess what's wrong in your project
I found the problem finally. There was a child animator with Apply Root Motion enabled that prevented the parent animator from working in builds (why it still worked in the editor is beyond me 🤷♂️). Disabling that seems to have no affect. Nothing to do with code finally. Sorry for the trouble.
Do you know the algorithm used in oxygen not included to simulate flowing in pipes?
is there a way to add colors to the debug console letters?
sure debug.log supports the <color> tag
Ow I did read something about that now that you say that everything come back up
I would like to create a multiplayer game that behaves like Minecraft.
Where a player will host a server locally and give his friends the ip address
and friends will be able to join through the ip address.
I created a small SignalR service that runs locally once the game starts.
However I can't figure how would I allow other players to connect
since just pinging the ip address of the host machine never seems to work and I stumbled upon a lot of suggestions of port forwarding\disable firewall\expose ports...etc
But how do games come ready to allow connection through ip without having to do all that?
I wanna implement it in a clean way.
You need port forwarding for minecraft to use a direct ip connection from a person's personal internet connection
TO avoid port forwarding etc you would typically use a Relay service
welcome to networking, you forgot NAT punchthrough. And, when you have done all of that most ISP's still wont let you through
@sly grove @upbeat path
I will check those out and get back to you
But is there a better approach that doesn't involve extra complications, maybe something other than signalR, since it was a pain to make it work in unity xD
Still prefer to write my own server though.
and I don't want dedicated multiplayer servers
just the ability to allow co-op, something like souls like games
There are dozens of networking solutions
why not look at Unity's own first party solution
Netcode for GameObjects supports Unity Transport and Relay
which supports peer to peer hosting
You can use any UDP/TCP/Websocket transport if you want something lower level outside of Unity
still need a server for it though
But those don't allow u to write ur own server logic right?
and I really wanna get into that
Of course they do..?
The issue has more to do with simply the fact that it's not easy to "connect to another computer using IP address." This problem doesn't apply to just your game, it also applies to Minecraft, and every single game that tries to do the same.
What about without Ip?
in minecraft there's another way which is you're able to see other servers by friends
doesn't that work the same but hides the ip address from the ui?
I'm not sure the technical details, but that's very likely achieved by having a middleman server acting as relay.
That just implies that there's even more server involvement.
You can't fix this completely just with software
wouldn't the server in this situation, tell one ip address which ip address to connect to? xD
I'm not sure the reasons of you choosing this approach, if the reason is that "I want players to host the servers so I don't have to pay for my own servers" then that's pretty much a pipe dream.
it ain't that simple
Afaik Minecraft Realms (if that's what you are referring to) are dedicated servers managed by Mojang.
Knowing the IP is not the issue
You simply can't connect to a computer through the internet when they're behind a NAT (which everyone is) without port forwarding or other workaround
that's the whole point
Their computer doesn't HAVE an IP on the internet when they're behind a NAT
even if your ISP allows that, which the vast majority do not for a 'home' internet connection
I am doing it for fun for now
but eventually I wanna be able to do that, my own servers run by players to avoid having a dedicated server hosted by me
I dont mind having an api to handle low level stuff like logging in and adding friends and seeing who's online and who has their server running...etc
but the actual game server itself, no money for that
Your computer <---> Your NAT < ---- Internet ---> My NAT < --- > My Computer
Our computers only have IP addresses in the local networks inside our homes. They don't have an internet IP.
You could use Epic's or Valve's free relay servers
you seriously need to learn how the internet actually works
That's fine and all, but whoever hosts the server has to deal with exposing their machine to the internet. There's no simple "double click this exe and it handles everything for you" that's simply unrealistic.
And yea, some users will be able to figure this stuff out
you think? Most can only barely find the on/off switch on their computers
well, ill go check what a relay server does and come back to annoy u with more questions 😄
Many kids end up following guides online to set up their own game server. This is probably not viable if each small lobby is expected to have their own server, but it can work with a game where hundreds of players can be on the same server.
I remember back when people were hosting their own Minecraft servers and port forwarding/NAT punch through was universally a headache to less tech savvy people, and that is still true today.
People used to use some services that act as a relay server for you. That obviously costs money to run.
Damn right it does, I run a relay server it costs me 5K USD/Month
if im doing spline generated geometry should i just use graphics api or make child game objects
which one tends to be more performant in the long run ?
once the spline is set they are static but when constructing them they change every frame with mouse movement if that matters
If you can get away with doing it only in the graphics API that's often much more performant
Especially if you can use Graphics.RenderMeshIndirect