as in this Gif, the white cube turns red when blue cude touches it. How to limit it to only one white cube gets triggered everytime?( it doesn’t matter which one )?
Have each white cube have a reference to the other one and only color this one red in OnTriggerEnter if the other one isn’t?
I would create a parent empty game object above the red cubes. Any time one of the cubes has an onTriggerEnter have it call a method in a script on the parent object. That script will turn the one that just signaled it red. Have that script also store which cube is already red and turn it back to white.
You can try something like this. Not tested code but it should work
private GameObject _currentTriggerObject = null;
public void OnTriggerEnter(Collider col)
{
if(_currentTriggerObject != null) return;
if(_currentTriggerObject.TryGetComponent<CubeComponent>(out var cubeComponent))
{
_currentTriggerObject = col.gameObject;
cubeComponent.TurnBlue(true);
}
}
public void OnTriggerExit(Collider col)
{
if(_currentTriggerObject == null) return;
if(_currentTriggerObject.TryGetComponent<CubeComponent>(out var cubeComponent))
{
_currentTriggerObject = col.gameObject;
cubeComponent.TurnBlue(false);
}
}
Keep in mind if this is for a racing game, all the movements and triggers will be calculated in one step (the physics step) and then all the trigger callbacks sent out. Their order is NOT guaranteed.
For instance, if player A is ahead of player B but they both cross the finish line on the same frame, the callback for player B might come first, or maybe player A.
It would be up to your code to recognize tiebreaking leads like this, perhaps by analyzing their positions.
Here is why, some timing diagram help: