How does priority/ simultaneity work in Unity?

In the project I’m working on, I have objects that can destroy each other. The trouble is, they can’t destroy each other at the same time–one always takes priority. Here is a simple example that will show the problem: I have two objects GameObject1 and GameObject2 with the following C# script attached:

public class Simultaneous : MonoBehaviour {
	
	public bool isOn = true;
	public GameObject otherObject;

	void Update () {
	if(isOn){
		otherObject.GetComponent<Simultaneous>().isOn = false;
		}
	}
}

Here, GameObject1 is assigned as GameObject2’s otherObject and vice versa. When I run this program, what I expect to happen is for both scripts to update simultaneously and set the other object’s isOn to false (i.e., both variables start true and become false). However, what does happen is GameObject1 sets GameObject2’s isOn to false and GameObject1’s isOn remains true. GameObject1 appears to have priority over GameObject2 even though they’re functionally identical.

Why is this? Is there any way to have both objects disable each other simultaneously?

Thanks for your help.

The code executes sequentially in Unity, always. The Update functions are called by Unity in a loop, and each executes to completion before the next starts.

The only way to have code execute simultaneously is via threads, and even then it only executes simultaneously if you have multiple processors or cores. And, you can’t execute Unity API functions via any thread other than the main application thread.

Unity does offer a form of parallelism by using Coroutines. However these still execute sequentially.

So, once your Update function executes on one of the objects, it disables the other. When the other Update function runs, it does nothing because it’s already disabled.

If you want them both changed at the same time, try using a third script that controls them both.

General computer rules are that nothing happens “at the same time,” and if you try, the order will be arbitrary. For example, the swap: a=b; b=a; turns them both into b, since they run one at a time.

Many problems like yours can be solved by checking state changes – check only at the moments when something switches to ON or OFF. For example, “turn on Obj 1” would be: if ob2 is ON, turn off Obj2 (and leave Obj1 off – we are both off); else turn on Obj1.

The “gain pain but always works” solution is to have a master script do the work. Make an “old” copy of everyone’s ON/OFF. Then use the old values to update the current. Then the order won’t matter, since the “old” copies stay the same.