Update function doesn't work if conditional statement is present.
Hi, this question is answered many times, but still this is not clear. I am trying to check a condition in update function and subsequently the function will be executed.
My code is:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class relationshipScript : MonoBehaviour {
public GameObject dropArea;
public Collider2D dropAreaCol;
void Start()
{
dropAreaCol = dropArea.GetComponent<Collider2D> ();
}
void Update()
{
Debug.Log ("preLog");
changeColor ();
Debug.Log ("postLog");
}
void changeColor()
{
if (dropAreaCol.bounds.Contains (transform.position)) {
dropArea.GetComponent<Image> ().color = Color.green;
} else {
dropArea.GetComponent<Image> ().color = Color.red;
}
}
}
I have declared the collider in start function itself as this was suggested in some answers for the same topic. But still update is called only once. I have also noticed that every question in which the "Update was not working", there was always a conditional statement in the update function. Is it something related to that?
Link to other relevant answer - This link also had answered the same topic with reference to conditional statement but it still is not clear.
Update wont stop like that unless you have an inescapable loop or something, but that will freeze the program. Guessing you have "Collapse" selected in the console.
In the case of a bad loop, the problem does not need to even exist within that script.
The only other thing that I've seen prevent Update running is something that prevents Start() from ending.
Answer by EmHuynh · Feb 18, 2016 at 08:22 AM
Hello, @navijha. I created a project with a scene with all necessary game objects and attached the needed components to test the script. There is no error, the Update function works. The color of the Image component of dropArea
is changed accordingly to the condition of the if statement in function changeColor
. The error in your project is caused by something else. Are there any other game objects or scripts that you think is the culprit?
Hello @EmHuynh. Thanks for the answer. You are right, the script is wrongly attached to different game object and so there was an error.