Critical sections in Unity?

Now this might be a stupid question, but there it goes. I know that all scripts should run in the same thread, but then I still cannot explain the following behavior:

In my game I have an object that I move around using the mouse cursor. Upon getting in the proximity of other objects, I “pick” them. The way I do it is that the objects to be picked constantly check in their Update() method if they are close enough to my main object, and if they are, they call a method on my main object in order to “register”. The first object that registers has a special status, setting a certain flag on my main object.

Problem is, due to random spawning on the map, it happens that two objects detect roughly at the same time that they are close enough to my main object to register and they both call the registering code. Through testing, I have found out that both picked up objects read that flag that the first object should set as unset, and they are both picked as “first objects”.

If this is running in the same thread, how can this happen? If the code is ran in the same thread, the call to “register” should be executed for one object, which would set the flag, and then the second object should be able to read it as set and no longer be considered also a first object.

I have tried using critical sections (using “lock(this)” in C#) but it seems to have no effect.

Any ideas?

Thanks.

All scripts are run in the same thread unless you specifically create threads using System.Threading. It’s impossible to execute Unity functions in threads regardless (aside from ones which just make use of .net functions, like Mathf). Check your code logic again.

You were true. It took the refactoring of most of the code to find the problem, but I have found it. That solved one issue and pinpointed the solution to another issue, which I still think it is a problem with Unity itself, but it can be worked around.

The problem is the following:

I have ObjectA waiting ObjectB to get close to it, so it can call a method on ObjectA. Now if by chance ObjectA doesn’t exist yet, and when it is created it is spawned directly in the range of ObjectB, ObjectB gets to call a method on ObjectA before ObjectA.Start() (overridden of MonoBehavior) is called. Now I can work around this by creating ObjectA first, then all instances of ObjectB, but still I thought Start() would be called like a constructor whenever the object is created and no other methods are called before it.