- Home /
Bool variable doesn't update its status
Hi, i have a problem... I create a Parent (EmptyGameObject) and its child (imported 3d model). The child object has a bool variable that change if it collide with an obstacle (tag "Obstacle"). I create a script for the Parent that load the bool variable ( VariabileBool classTest = cubo.GetComponentInChildren<VariabileBool>();
) but there's a problem... The value of bool variable, don't update when in the children script change is status (become true)... How can I resolve this problem? Sorry for my bad English...
VariabileBool script (on Child object):
public class VariabileBool : MonoBehaviour
{
public bool variabile = true;
}
Parent script for read the variable:
public class LettoreVariabile : MonoBehaviour
{
VariabileBool classeVariabile;
public GameObject cube;
private void Start()
{
classeVariabile = cube.GetComponentInChildren<VariabileBool>();
}
void Update()
{
Debug.Log(classeVariabile.variabile);
}
}
Answer by Casiell · Mar 19, 2020 at 09:52 PM
You bool a public field in a MonoBehaviour class. That means, it's serialized by Unity.
Now what serialization means in this situation: the variable value was saved in a state it first was on that gameobject and for that specific gameobject Unity will ignore any changes you do to initial variable value.
You should either change that value in Start, or change it in inspector for that component
I was looking at this question, and thinking what the hell is going on, but you are absolutely right :P It's just saving the inspector value and doesn't care about that script anymore. Good catch!
Thanks... How can i resolve this via script? I need this because when a child object hit an "obstacle" the bool variable will change to "true" automatically (OnCollisionEnter)