#archived-code-advanced

1 messages · Page 110 of 1

untold moth
#

Yes, although initiating a refresh (Ctrl + R) could also work

elder heath
#

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

hallow aurora
#

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

earnest heron
#

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 ?

regal olive
#

@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.

distant fable
#

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

Get the ASCII FBX Exporter for Unity package from 8Bit Goose Games, Inc and speed up your game development process. Find this & other Modeling options on the Unity Asset Store.

#

Please share if you have any other asset or method to export FBX at runtime, Thanks!

earnest heron
still timber
#

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.

regal olive
fallow echo
regal olive
#

He said he had implemented this by custom verlet integration. What if he does some kind of velocity smoothing for the start point there?

stuck plinth
regal olive
dusty wigeon
earnest heron
# dusty wigeon You can have your physics update in FixedUpdate and simply lerp towards the resu...

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 ?

misty glade
#

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.

dusty wigeon
dusty wigeon
earnest heron
misty glade
bleak sand
#

Hi

misty glade
#

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

dusty wigeon
#

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.

misty glade
#

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

dusty wigeon
#

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)

misty glade
#

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

dusty wigeon
#

Are you able to profile ?

misty glade
#

In unity? I imagine so?

dusty wigeon
#

Is it in editor ?

misty glade
#

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

dusty wigeon
#

You are trying to debug the editor or a build ?

misty glade
#

a build

#

er, sorry, I mean, I'm trying to debug in the editor (versus on device)

dusty wigeon
#

Have you tick the box that enable you to debug O.o

misty glade
#

but i'm not debugging any editor code (like custom inspectors or anything like that)

#

where is this magic box? 😛

dusty wigeon
#

Are you trying to debug the editor or the build

misty glade
#

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'"

dusty wigeon
#

No idea.

misty glade
#

because I would pay $$$$$$$ for a button like that..

dusty wigeon
#

Only times it happened, I restarted computer and was able to debug again after.

misty glade
#

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 🤷‍♂️

dusty wigeon
#

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

misty glade
#

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"

dusty wigeon
#

Rider/Visual Studio are pretty much your only option. You have Visual Studio Code, but I would really recommend.

#

Rider is not free though

misty glade
#

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

scenic forge
#

It's not any different from VS debugging, you have conditional breakpoints, stepping, viewing stack, variables, etc, all the same.

misty glade
#

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.

earnest heron
#

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.

fallow echo
#

Generally, you need to smoothen the whole thing, probably... or at least apply some smoothiness to a few of the particles

earnest heron
earnest heron
marsh saddle
#

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.

misty glade
#

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. 😦

sly grove
#

definitely don't do something like attempting a version upgrade without making a commit first!

lavish spade
#

Sometimes help migrate things over, worst case scenario

proud coral
#

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.

marsh saddle
#

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🥳

wet sail
#

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

wet sail
#

it is

#

editor code question

upbeat path
wet sail
#

figure what ?

upbeat path
#

that it is a code question

wet sail
#

im the one that decides that

upbeat path
#

no you are not, the people answering the questions decide that

wet sail
#

there's no toggle.
in editor, setting Tools.viewTool == ViewTool.FPS doesn't emitate that.

wet sail
#

but sure

orchid cedar
#

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?

orchid cedar
#

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

upbeat path
#

But if you have exited Play mode, surely your OnDisable should have handled that, there would be nothing for the reloadevent to do

orchid cedar
#

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

upbeat path
#

I can't remember the exact sequence events in this situation, it may be worthwhile chucking some Logs in there just to be sure

orchid cedar
#

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!

upbeat path
#

excellent

gleaming sail
#

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?

olive cipher
#

if so most of the time you can just scale tilesize by multiplying the x/y seed of each noise layer with a multiplier

gleaming sail
#

At least, thats how I understand it

raven lintel
#

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

compact ingot
proud steeple
#

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.
proud steeple
raven lintel
compact ingot
# raven lintel Im unsure what you mean by the second part; yes, technically ypu dont have to us...

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.

untold moth
#

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

raven lintel
#

Hmm, i’ll look into those.

scenic forge
#

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.

compact ingot
#

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

raven lintel
scenic forge
#

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.

raven lintel
compact ingot
scenic forge
#

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)

raven lintel
#

This is for Standalone Windows and MacOS

scenic forge
#

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.

tall ferry
#

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.

kindred spindle
#

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.

upbeat path
kindred spindle
#

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.

upbeat path
#

it would help if you shared your !code both for the BinaryWriter and the BinaryReader

thorn flintBOT
kindred spindle
#

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.

kindred spindle
#

any ideas what my problem is?

plush hare
#

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

kindred spindle
plush hare
#

I'm surprised that function even allowed you to input a vector3 at all...

kindred spindle
#

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

tall ferry
proud steeple
#

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.

untold moth
tacit harbor
#

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?

twilit jetty
#

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,
});

slow jay
#

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

untold moth
slow jay
#

if I just track previous mouse position and calculate the delta by using current mouse position and previous mouse position, it'll be shit

lucid crane
#

For detection, start position - end position / time Or just use the mouse velocity.

sage radish
worldly pecan
#

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

untold moth
#

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.

worldly pecan
#

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?

untold moth
#

The CPU has nothing to do with that at this point.

worldly pecan
#

Ok thanks! I guess this makes sense with multiple queues

untold moth
#

GPUs have something like a command processor that processes the queue/s. It also manages the fences and stuff I think.

worldly pecan
# untold moth The CPU has nothing to do with that at this point.

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

untold moth
# worldly pecan Oh so what you're saying is that the fence exists on both of the queues, when it...

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.

https://docs.unity3d.com/ScriptReference/Graphics.html

worldly pecan
#

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

untold moth
#

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.

worldly pecan
untold moth
#

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.

worldly pecan
#

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

worldly pecan
untold moth
#

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.

white narwhal
#

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.

tropic vigil
white narwhal
#

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, ...)?

tropic vigil
# white narwhal Is it possible to get this kind of crash (Memory access violation & such) becaus...

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).

untold moth
untold moth
stuck plinth
#

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

white narwhal
# untold moth Try playing and reproducing the crash with the debugger attached. It should brea...

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(), ...

untold moth
#

Anyways, with a debugger attached you might be able to gather enough info to guess what the cause is.

white narwhal
untold moth
white narwhal
#

(Sorry I hope dumping screenshots like that isn't considered spamming)

untold moth
white narwhal
#

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.

untold moth
white narwhal
untold moth
white narwhal
untold moth
#

Yeah. Especially in an il2cpp

white narwhal
#

I've always assumed that code stripping issues aside il2cpp fully supports reflection.

untold moth
#

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

crisp temple
#

~~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

sage radish
#

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.

crisp temple
sage radish
stuck plinth
#

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 😅

upbeat path
#

of course you can use the Preserve attribute to prevent stripping if you need to

#

very handy for dynamic generics

azure meadow
#

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? 🤔

upbeat path
#

I honestly dont see the point of that above TryGetComponent

sage radish
azure meadow
#

Interesting, I assumed that was pretty much what assert was doing

azure meadow
upbeat path
#

also things like this should come out in testing

azure meadow
# upbeat path but it's not short is it?
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 😛

upbeat path
#

well, yes if you totally ignore the other 4 lines of code you wrote to do it

sage radish
#

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.

upbeat path
sage radish
azure meadow
#

and readability 🤷‍♀️

upbeat path
#

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

sage radish
sage radish
upbeat path
#

why do you need the asset? A Null ref is just as good

azure meadow
#

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" 🤔

upbeat path
#

I dont see it, an Assert or a Null Ref both mean 'I fucked up'

sage radish
azure meadow
#

you will crash very far from the faulty GetComponent

upbeat path
#

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

azure meadow
upbeat path
#

because then you pay no additional overhead in a production build

sage radish
#

Potential overhead is a valid concern, but that's why they came here asking if they can inline it like the Unreal macro.

upbeat path
#

Aggresive inlining can actually detrimentally affect performance

sage radish
#

Sure. Do you think that is the case here?

upbeat path
#

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

white narwhal
#

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.

upbeat path
#

MS Docs would disagree with you

#

I personally have never seen a performance benefit from aggressive inlining worth a damn

white narwhal
#

I use it on small functions that get called 10000+ times per frame and it help a lot

upbeat path
#

ok, but if I had code that needed calling 10,000+ times per frame the word 'Refactor' would spring to my lips

sage radish
#

10,000 doesn't even seem that much to me for a hot path.

white narwhal
#

Yeah that's like the minimum

upbeat path
# white narwhal Or this

So you're concerned about performance and yet you declare a property to save you typing 16 characters

scenic forge
#

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.

azure meadow
#

yeah, don't even use Physics.defaultContactOffset, just find out the default value and hardcode the 0.01f everywhere in your code 🙃 🙃

upbeat path
#

I am just way too old school for shit like this

stuck plinth
white narwhal
#

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).

upbeat path
dusty wigeon
white narwhal
#

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.

dusty wigeon
azure meadow
upbeat path
white narwhal
#

Thankfully Unity has inlined it so it almost entirely goes away in a release build

dusty wigeon
white narwhal
dusty wigeon
# white narwhal 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.

white narwhal
#

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.

dusty wigeon
#

In your case, sure do it. There is no reason apparent to not do it. But it will mostly not matter.

stuck plinth
#

looks like it's being called 200k times per frame though!

dusty wigeon
#

That would be mostly the issue, but even at that amount I would supprise that it goes to even a fraction of a ms

white narwhal
#

Yeah I know. I'm doing some stuff over many GameObjects and I should have tired out for this project ECS I think.

dusty wigeon
#

Or use better code ?

#

Pretty sure you could reduce the logic, stagger the logic or even use threading where it make sense.

white narwhal
#

I mean with 1000s of entities even just having an update method amounts to a decent amount of time.

dusty wigeon
#

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 ?

white narwhal
#

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.

dusty wigeon
upbeat path
white narwhal
#

Alright, well, I think I can live with doing something wrong like Unity's actual C# code.

upbeat path
white narwhal
white narwhal
upbeat path
#

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?

chilly moon
compact ingot
#

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.

stable rain
#

Very easy to complain

#

Not so easy to do it

hardy copper
#

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?

worldly pecan
steel snow
#

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

wet sail
#

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" ???

lucid crane
#

Sometimes different formats or 3d softwares have flipped x and y, but sometimes y and z are flipped in the case of blender.

wet sail
#

isn't supposed for "without bake" to at least have a rotation of (0,180,0) to mimic baking ?

lucid crane
#

Or the rotation conversion is ignored by default. Can’t say I’m an expert

wet sail
#

not children. i checked.

#

but idk about rotation. that;s why im asking its confusing

azure meadow
#

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

wheat nexus
#

does anyone here have any idea how to make a voice recognision keyword system compatible with photon voicechat?

sly grove
#

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

azure meadow
#

also... what happens if I manually nuke a field in the yaml 👀

sly grove
#

what does "nuke" mean

azure meadow
#

delete 😅

sly grove
#

nothing much

#

you lose that serialized field data

azure meadow
sage radish
azure meadow
#

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 🤔

sage radish
#

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.

azure meadow
sage radish
azure meadow
#

there is NonSerialized . I can still show it in inspector with reflection black magic 🤔

sage radish
azure meadow
#

ohhh, I see what you mean 🤔
I will experiment 👀

lucid crane
#

You can hook up custom inspectors with conditions to hide them in the inspector

#

Not sure if that is what you wanted lol

azure meadow
#

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 👀

sweet niche
#

@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.

azure meadow
#

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 😛 )

sly grove
azure meadow
#

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 😛

tall ferry
silent dagger
#

I still try to manage multi-tile terrain in runtime but when I try to smooth the terrain the connection gets broken 😦
Any advice?

dawn mesa
#

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.

untold moth
#

And while we're at that, the solution would depend heavily on how you have the movement implemented.

dawn mesa
#

How do I access the ground normal?

untold moth
untold moth
dawn mesa
#

Just the name of it is fine

#

With a character controller and the move function

untold moth
dawn mesa
#

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

untold moth
#

How are you preventing your character from jumping infinitely?

dawn mesa
#

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.

untold moth
dawn mesa
#

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

untold moth
#

It's not expensive. Are you planning to do thousands of them per frame?

dawn mesa
#

nope, but on all entities which use the collision script

untold moth
dawn mesa
#

Which includes enemies.

untold moth
#

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.

dawn mesa
#

True, but I've worked on enough 2d games to dread editing collision code later, since chances are a bunch of stuff breaks.

untold moth
#

That's part of development. Use version control if you're afraid to make breaking changes.

earnest heron
#

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 😄

untold moth
earnest heron
untold moth
earnest heron
untold moth
#

I don't know what you mean by "no chance". You should've got the direction from the tip to the bait.

earnest heron
#

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.

wheat nexus
#

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

sly grove
wheat nexus
#

thanks

chrome ermine
#

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?

upbeat path
chrome ermine
# upbeat path 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

upbeat path
wet sail
chrome ermine
#

is it somewhat caching the slots beforehand

upbeat path
chrome ermine
#

oh so its allocating in batches if i exceed

wet sail
#

i was banging my head for 26hours straight not joking

#

for it to be bugged

upbeat path
#

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

chrome ermine
lucid crane
hushed fable
stuck plinth
upbeat path
#

but it is a fine line to walk

hushed fable
upbeat path
#

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

stuck plinth
#

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 😛

chrome ermine
#

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

upbeat path
stuck plinth
chrome ermine
upbeat path
chrome ermine
#

thanks everyone again

upbeat path
stuck plinth
#

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#!

upbeat path
stuck plinth
#

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!

upbeat path
hushed fable
earnest heron
#

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.

untold moth
brisk pasture
trail zealot
#

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

untold moth
crystal walrus
#

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()

earnest heron
earnest heron
#

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)

tall ferry
earnest heron
#

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.

earnest heron
tall ferry
brave cairn
#

Chapter 6

#

I have successfully implemented all blendtree models in Rukhanka animation system, and they are perfectly coincides with Unity's.

untold moth
lilac spoke
#

.json has no problem saving dictionaries, right?

untold moth
upbeat path
lilac spoke
#

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

upbeat path
#

you wrote your own json library?

lilac spoke
#

no. sorry that was misguiding.

upbeat path
#

so which library are you using, there are many

untold moth
brisk pasture
lilac spoke
brisk pasture
#

its a very complete implementation

lilac spoke
#

and this helper method works to some extend. it already saves something, but the values are empty

brisk pasture
#

just use a lib that supports it from the start instead of hacking around it

upbeat path
untold moth
#

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

lilac spoke
#

yeah maybe i should. but i havent touched that code for months lol. and its my first time writing a save system.😓

untold moth
upbeat path
lilac spoke
#

i think, i am indeed not using any library... maybe thats why

upbeat path
#

\wtf do you think JsonUtility is if not a library?

brisk pasture
#

then what are you using, the built in one JsonUtility?

lilac spoke
#

na nvm. i found it. its JsonUtility

brisk pasture
#

yeah that does not support dictionary

#

it only supports the same types unity can already support in the inspector

lilac spoke
#

ah ok thanks

brisk pasture
#

the one i linked above is a full featured one

untold moth
#

Though you can implement your own serializer for dictionaries specifically and keep on using JsonUtility.

brisk pasture
#

its what 90% of people use for json in unity these days if they need more then JsonUtility

lilac spoke
# untold moth Though you can implement your own serializer for dictionaries specifically and k...
        // 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

lilac spoke
untold moth
lilac spoke
#

the initially yes. no values show up for the moment, but ill look into it first

untold moth
#

So, it doesn't work? Then you'll need to debug it.

brisk pasture
#

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

kindred spindle
#

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

sly grove
kindred spindle
# sly grove what do you mean by "work with binary data"? All data is binary data. What are y...

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

sly grove
#

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.

kindred spindle
# sly grove for example if you want to write a position, you could write the X, Y, Z float v...

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.

sly grove
#

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

#

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

kindred spindle
sly grove
#

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

kindred spindle
#

is this too much to ask for protobuf?

sly grove
#

Have you considered using Asset Bundles?

kindred spindle
sly grove
#

You probably should

kindred spindle
# sly grove You probably should

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#

misty glade
#

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
}
white pulsar
#

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

fresh salmon
#

HTTP 403 is the "Forbidden" error: the repository may be private so you cannot see it without being logged in.

white pulsar
#

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

fresh salmon
#

You'll have to show some code

white pulsar
#

ignore my cave-man usage of Thread.Sleep, the actual production code will use async await/editor coroutines

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

#

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

white pulsar
#

Wait

sly grove
#

Try:

var url = $"https://api.github.com/repos/{GitHubRepo}/releases/latest";
Debug.Log(url);```
white pulsar
#

I just noticed my code is stupid

#

Guys I'm not checking while(!completed)

#

nvm, it still throws it.

white pulsar
sly grove
fresh salmon
sly grove
#

that being said - any reason you're using HttpClient and not UnityWebRequest?

sly grove
#

UnityWebRequest will fix that too I believe

white pulsar
#

i didnt know about unity web request

#

i'll try that out

#

time to read about the web request documentation

fresh salmon
#

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

white pulsar
#

yup, i replaced httpclient by UnityWebREquest.Get(url) and it has returned the json data

#

thanks guys, very cool coolcaco

fresh salmon
#

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.

sly grove
#

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

fresh salmon
#

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"

misty glade
#

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)?

sage radish
misty glade
#

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)

sage radish
# misty glade It's some sort of component that identifies a canvas location for a tooltip of a...

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.

misty glade
#

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

sage radish
#

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?

misty glade
#

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..

azure meadow
#

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 🤔

sly grove
#

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

azure meadow
#

this time I am just curious 😅

#

how flexible is the Invoke thingy 😅

sly grove
#

The delegate type has to match

#

that's the only rule

sly grove
azure meadow
#

since we are here... is there a real difference between Event/Action and UnityEvent/UnityAction? 🤔

sly grove
#

Yes

azure meadow
#

I am torn between doing as the romans and unity doesn't always do the smart thing 😅

sly grove
#

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.

azure meadow
#

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 🤔

sly grove
#

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

azure meadow
#

or a "you tried to access this thingy but it was destroyed"

sly grove
#

That's what MissingReferenceException is

azure meadow
#

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 🤦‍♀️

sly grove
azure meadow
sage radish
#

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.

opal sparrow
#

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.

  1. 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.

  1. 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?

olive cipher
#

I think VRchat has pretty good devlogs about how their stuff works

jaunty swallow
#

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

upbeat path
jaunty swallow
#

GetFriends isn't awaitable

upbeat path
#

I meant in the foreach friend will not be filled until you actually enter the loop

jaunty swallow
#

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

upbeat path
#

friends, yes, but it looks like you are looking at friend which at that point in your code is null

jaunty swallow
#

but the friend is just an index from friends, implying that the function didn't work correctly

upbeat path
#

no, friend will not exist until the foreach is executed which it has not yet been

jaunty swallow
#

the foreach doesn't correlate to setting friends in any way, that's why I don't understand

upbeat path
#

read what I am writing, I'm talking about friend not friends

jaunty swallow
#

yes but I don't set friend in the loop?

upbeat path
#

what? Do you not know how foreach works?

jaunty swallow
#

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

upbeat path
#

yes, and creates a local variable, friend, which comes into scope when you are INSIDE the foreach loop

upbeat path
jaunty swallow
#

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?

upbeat path
#

yes

jaunty swallow
#

thats not the issue

#

obviously it will be null

#

my problem is that the list isn't assigning friend

upbeat path
#

you should be inspecting the var friends on the previous line if you want to see the contents

jaunty swallow
#

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

long ivy
#

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

upbeat path
#

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

jaunty swallow
#

it doesn't, that was my issue

#

it goes straight to catch in the foreach line

long ivy
#

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

upbeat path
#

also the code containing the try catch

jaunty swallow
#

it's throwing because it's null

jaunty swallow
long ivy
#

then you haven't proven GetFriends isn't throwing an exception by itself yet and your screenshots so far have been useless

upbeat path
#

man, this is code advanced, you should know the difference between a null variable and a null list

jaunty swallow
jaunty swallow
#

nothing to see here

long ivy
#

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

jaunty swallow
upbeat path
#

you said it goes straight to the catch in the foreach, the catch is clearly OUTSIDE the foreach

jaunty swallow
#

it goes to catch when it gets to the foreach...

#

wat?

upbeat path
#

yes, because firends is null

jaunty swallow
#

that is what I've been saying

#

this entire

#

time

long ivy
#

or GetFriends has thrown an exception because you didn't do some configuration correctly

upbeat path
#

\no, you said a null list which is totally different

long ivy
#

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

upbeat path
#

It'll null ref on the ToList

jaunty swallow
# long ivy no dude, your first screenshot hasn't entered the foreach yet and friends hasn't...

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

long ivy
#

so you can now rule out the entirety of the foreach loop

upbeat path
#

So you need to be looking in the SteamWorks docs to see why GetFriends is returning null

jaunty swallow
#

well facepunch's docs are useless

#

hence why i'm here

upbeat path
#

but this is not a Unity problem

jaunty swallow
#

indirectly it is

upbeat path
#

what, the fact that a 3rd party has useless docs is a Unity problem how?

jaunty swallow
#

I'm just looking for support that I thought unity devs are likely to relate to

stuck plinth
jaunty swallow
#

why are you so pressed

stuck plinth
#

Internal being a reference to the steam friends interface which needs to be initialized at some point

jaunty swallow
long ivy
#

is that your steam app id and did Init throw any exceptions?

jaunty swallow
#

its spacewar app id

#

and no it doesn't

#

the entire steam framework runs fine, its just the GetFriends

long ivy
#

the stupidest reason this could fail is you don't have steam running

jaunty swallow
#

nah I do dw

#

I mean it's throwing this

    throw new Exception("INVALID");
long ivy
#

are you 100% sure your init isn't throwing, then?

jaunty swallow
#

but I've gone through the SteamClient.Init with the debugger + I have other logic after it and it all runs fine

jaunty swallow
#

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

upbeat path
#

The obvious thing to do here is create a simple Console App which implements these API's, it will be much easier to debug

long ivy
#

it worked instantly for me np in a test project

jaunty swallow
#

🤔

#

in unity or console

long ivy
#

unity

jaunty swallow
#
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

long ivy
#

the only way I can replicate your results is if init didn't run

jaunty swallow
#

and your valid is returning true?

long ivy
#

if init ran, yes

upbeat path
#

Console.WriteLine in Unity code???

jaunty swallow
#

well I didn't think this was a simple fix anyway 🤷‍♂️

#

oh true I just pasted his code lmao

long ivy
#

I think it is a simple fix, your init isn't running. Prove that it is. Did you disable domain reload?

jaunty swallow
#

it seems to be running the callbacks normally anyway

jaunty swallow
#

also my friends list says I'm playing spacewar

jaunty swallow
long ivy
#

did you try turning it off and on again? Both Unity and steam

jaunty swallow
#

this looks suspicious tho

jaunty swallow
#

wait I might have found it

#

SteamUser.OnSteamServersConnected never gets called

long ivy
#

at this point you should be using a minimal test project instead of flailing around in yours where something has clearly gone wrong

jaunty swallow
floral marten
#

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)

misty glade
#

Is it because the instantiate chain serializes/deserializes in order to resolve references, so the global id isn't yet resolved or something..?

floral marten
#

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

sage radish
floral marten
#

I really don't like getting into DelayCall stuff

worldly pecan
#

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.

calm elbow
#

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

worldly pecan
dusty wigeon
# worldly pecan

You could simply express your density equation in function of a position and then sample the equation for a discrete amount of position.

worldly pecan
dusty wigeon
#

You are better off optimizing but having good caching system than attempting to find the equation that fits your problem that seem kinda complex.

worldly pecan
#

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.

dusty wigeon
#

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

worldly pecan
#

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.

dusty wigeon
#

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,

worldly pecan
#

Is there a channel here for that?

dusty wigeon
#

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.

dusty wigeon
#

d(ray(Distance)_x) = Densitity
d(ray(Distance)_y) = Densitity

worldly pecan
dusty wigeon
#

2 unknown, 2 equation.

worldly pecan
#

The only unknown is t, the parametric parameter or distance along the ray

dusty wigeon
#

Oh right, I understand now it is a less or equal problem

worldly pecan
#

it eventually reduces down to 0 = Ct^2 + Ct + C where C are constants

dusty wigeon
#

Yeah, you almost need to use what I said.

#

It is a minimization problem

worldly pecan
#

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

dusty wigeon
#

Yeah, then minimize the parameter

worldly pecan
#

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

dusty wigeon
#

I mean, try it but

compact ingot
worldly pecan
#

Is that the theory behind Marching cubes? I guess I could construct the triangles and use existing code for line intersects triangle algorithms…

compact ingot
#

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.

worldly pecan
#

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.

river oar
#

I know this is old but you just saved my life, thank you ❤️

graceful pumice
#

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

worldly pecan
# worldly pecan Hey guys, I'm asking because I'm pretty bad at math. I have a 3D grid/map with a...

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.

regal olive
#

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.

brave helm
tropic vigil
# regal olive I am working on a visual novel that uses a bunch of short videos, I am wondering...

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.

worldly pecan
regal olive
#

I currently have manual nodes in my setup in certain places for preloading but it's kind of messy and unintuitive

tropic vigil
# regal olive I currently have manual nodes in my setup in certain places for preloading but i...

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
regal olive
#

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?

dusty wigeon
regal olive
#

my head is fried after a long day of struggling with editor tools

dusty wigeon
reef helm
#

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.

devout hare
reef helm
devout hare
reef helm
#

thank you

upbeat path
cold canyon
#

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

upbeat path
# cold canyon Hello everyone. I have a Free Camera System that moves the camera in any directi...

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...

somber swift
cold canyon
somber swift
#

I thought that would be a ton easier than any algorithmic approach

cold canyon
#

maybe you are right

somber swift
#

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

grand dagger
#

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.

https://gdl.space/ayeriyeqex.cs

shy nebula
grand dagger
shy nebula
grand dagger
#

yeah

#

its pretty much the same

thin mesa
#

Quaternion.Lerp and Quaternion.Slerp always take the shortest path to the target rotation

lament salmon
grand dagger
lament salmon
#

Just make sure to keep track of the floats yourself instead of reading from eulerAngles

tidal escarp
#

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?

devout hare
tidal escarp
devout hare
#

Sure but I don't know much about it, if you google for "integrating unity with react native" there's a lot of resources

tidal escarp
#

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

devout hare
#

Maybe start with the docs and ask when you run into issues

tidal escarp
#

okay thank you

short junco
#

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

midnight violet
short junco
midnight violet
#

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

azure meadow
#

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 😅

sage radish
# azure meadow What is your go-to, unity friendly, serializable Dicitonary/Map/Hashtable? 🤔

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.

azure meadow
#

Do I need a custom drawer? 🤔
probably, right?

sage radish
#

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.

azure meadow
#

Riiight, i've kinda done that with a list of a struct with two values (not generic, it was a very adhoc solution 😅 )

grave raft
#

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

humble leaf
#

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).

grave raft
dusty wigeon
#

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.

stuck plinth
#

but in theory yes!

azure meadow
#

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 😅

hushed fable
tropic vigil
misty glade
#

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)

sly grove
misty glade
#

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

sly grove
#

since you did new

misty glade
#

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?

sly grove
#

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

misty glade
#

oh uh.. and then what, set it in the ctor/init? i guess that's fine

sly grove
#

Set it in the inspector

#

I'm assuming this field is serialized, since you got a serialization error

misty glade
#

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

sly grove
#

If you don't want to serialize it then you should not make it serialized, and set it in Awake

sly grove
#

if you don't want to - that's what Awake is for

misty glade
#

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

sly grove
#

if you want to show a nonserialized field in the inspector that's what a custom editor is for - or something like Odin

misty glade
#

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)

fickle sapphire
#

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

untold moth
#

And expand the finish item

fickle sapphire
#

ok one sec

fickle sapphire
#

here's a different frame

untold moth
fickle sapphire
#

ahhh ok

untold moth
# fickle sapphire

Can you take a screenshot with only the second level of the hierarchy visible as well?

fickle sapphire
#

yep

#

the majority of fixedupdate's time is due to the contactmanagerdiscreteupdate

#

I can optimize that, I'm not realy concerned about it

untold moth
# fickle sapphire

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.

fickle sapphire
#

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

untold moth
fickle sapphire
#

ok thanks for your help

#

you're 100% right

crisp temple
# fickle sapphire

10kb of garbage per frame will chug on mobile, I'd definitely look into that if I was you

fickle sapphire
midnight violet
#

I guess these are editor screenshots, right?

fickle sapphire
#

no they are profiled on the android build and then imported into the editor

delicate wagon
#

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```
untold moth
delicate wagon
untold moth
#

But it's an easy thing to test. Just remove the Resources folder temporarily.

delicate wagon
#

Building a test as we speak

untold moth
#

You can also try opening the APK as a zip file and exploring it's contents.

#

Or use android studio analyze apk tool

delicate wagon
#

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?

untold moth
#

I don't think the engine itself takes 800mb, could it?

delicate wagon
#

Nah. I've seen builds of less than 100mb. Also, it shouldn't have shrunk as much without resources if that were the case

untold moth
#

Oh wait, it was 1.2 GB before

#

Maybe that's the uncompressed size?🤔

delicate wagon
#

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

delicate wagon
#

Yeah with the latest build (the one without resources)

midnight violet
#

Is there an package extension file next to the APK?

delicate wagon
#

Nope, no extension file

#

Some extra information: This is the build with resources folder

plucky terrace
#

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!

long ivy
#

unless you add more context, we can only guess what's wrong in your project

plucky terrace
#

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.

timber flame
#

Do you know the algorithm used in oxygen not included to simulate flowing in pipes?

stoic otter
#

is there a way to add colors to the debug console letters?

upbeat path
stoic otter
#

Ow I did read something about that now that you say that everything come back up

sly aurora
#

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.

sly grove
#

TO avoid port forwarding etc you would typically use a Relay service

upbeat path
sly aurora
#

@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

sly grove
#

why not look at Unity's own first party solution

#

Netcode for GameObjects supports Unity Transport and Relay

#

which supports peer to peer hosting

hushed fable
#

You can use any UDP/TCP/Websocket transport if you want something lower level outside of Unity

upbeat path
sly aurora
#

But those don't allow u to write ur own server logic right?
and I really wanna get into that

sly grove
#

Of course they do..?

scenic forge
#

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.

sly aurora
scenic forge
#

I'm not sure the technical details, but that's very likely achieved by having a middleman server acting as relay.

hushed fable
#

You can't fix this completely just with software

sly aurora
scenic forge
#

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.

hushed fable
sly grove
#

that's the whole point

#

Their computer doesn't HAVE an IP on the internet when they're behind a NAT

upbeat path
sly aurora
sly grove
#

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.

hushed fable
#

You could use Epic's or Valve's free relay servers

upbeat path
scenic forge
#

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.

hushed fable
#

And yea, some users will be able to figure this stuff out

upbeat path
sly aurora
#

well, ill go check what a relay server does and come back to annoy u with more questions 😄

hushed fable
scenic forge
#

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.

upbeat path
steel snow
#

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

sly grove
#

Especially if you can use Graphics.RenderMeshIndirect