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.