OnTriggerEnter() does not synchronize variables with Update()
Hello people,
I have a scene with 3 objects(rigid bodies) and 1 trigger. I have attached a script to an EventSystem that has an array of GameObjects and should do the following. The first object of the array can be moved and when it collides with the trigger object, it can't be moved anymore in contrast to the next object in the array. When the second object collides with the trigger and then we can move the next object and so on.
This is my script
public class SystemMove : MonoBehaviour {
public float moveSpeed = 5;
public GameObject[] objects;
int number = 0;
void Update()
{
//Debug.Log("Number in UPDATE is : " + number); // It still prints 0 despite being incremented in OnTriggerEnter()
//Debug.Log("objects.length in UPDATE: " + objects.Length); // Prints 3
objects[number].transform.Translate(moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
if(other.name == "Trigger")
{
number++;
Debug.Log("objects.Length: " + objects.Length); // Prints 0 WHY??????
Debug.Log(" Number: " + number); // Prints 1
}
} }
So why does OnTriggerEnter() prints 1 for the number variable and 0 for objects.lenght, while Update() prints 0 for number and 3 for objects.length.
Why are they not sychornized?
I don't know if EventSystem is the right object to attach this script. Maybe that is the problem, but the synchronization problem was really unexpected
Answer by Bunny83 · Aug 15, 2019 at 12:40 AM
You most likely attached this script to multiple objects at once. One script instance probably has it's object list initialized while the other one has not. We can not tell you more since we have no idea how your scene looks like, which objects are in the scene and which script is attached to which object(s).
Anyways you can pass a context object to your Debug.Log calls as second parameter. When you click on the log message in the console, Unity will highlight that context object so you know where it came from
Debug.Log("OnTriggerEnter:: Number: " + number, gameObject);