Use of statics and viable alternatives... am I doing this right?

I’ve been doing some research on race conditions and statics, and having to find the root of a problem which involves said race conditions is something I don’t want to do. Yet I’m unsure of how to avoid the race condition. I’ve researched Singletons, but I’m not sure how they apply to Unity with prefabs.

What is a good alternative?

I began to rewrite my reference code to include static getter functions but then I realized just now that this may prevent duplicated code but it won’t prevent a race condition because anything which has a reference to the object can obviously just change something without my knowledge!!!

Are you doing a lot of multi-threading? Where are these race conditions occurring?

What are you using the statics for? Are you talking about static properties?

What is the problem you’re attempting to solve?

I’m just trying to get references to my objects across different scripts. I suppose I should have thought about if I would have that kind of problem atm I don’t even know how to use multithreading, though I barely know what it is. I’m not having any race conditions. I’m using the statics as a way to get references across scripts. Ie. If I have a reference to my camera script 1 and need it in script 3, I do this:localCameraRef = Script_1.playerCamera where the playerCamera is a static object…

How would you get a race condition then?

A race condition is when the state of some value in memory changing being dependent on the order of operation. Two bits of code are “racing” towards that spot in memory, and if one beats the other, it may result in a faulted state.

This usually happens in multi-threading because it’s hard to control the speed of each thread relative to one another, and therefore have to hault a thread to wait its turn so that its sure the block of memory is not in a faulted state.

In single-threaded code, it’s much easier, since you don’t have multiple threads (unity is single threaded). Code just has to be ordered correctly (hence the Update/LateUpdate options, and the execution order options).

It’s usually considered bad design to use globals the way you describe, but that’s not really a race condition.

If you’re bothered that some line of code changes the reference… well make the setter of the property private so that only the class which owns the reference can modify it and signal if it changes.

Furthermore, instead of storing local references, you could always just grab a reference from the static property. If it ever changes, you automatically get the new reference the next time you access it.

1 Like

Yeah, I understand all that now. What I was doing was grabbing references from statics for use in other scripts like you said, I just mistakenly assumed that would cause problems with race conditions. Ugh. How embarrassing :stuck_out_tongue: