Warm tip: This article is reproduced from stackoverflow.com, please click
c# unity3d

Bool variable doesn't update its status

发布于 2020-06-03 12:06:57

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);
    }
}

img

I tried to update the status of bool in Void Start(), but doesn't work... once the variable has taken a state, it does not change...

Questioner
upstagesum
Viewed
10
Halil Cosgun 2020-03-20 20:18

You can try to access VariabileBool object from another object with this way;

  • create an empty VariableBoolObject in your scene.
  • Attach VariableBool class to the VariableBoolObject. (simple drag and drop process)
  • create second empty lettoVariable object in your scene. Then attach lettoVariable script to this object.
  • Then, open your scene select LettoreVariabile in your scene hierarchy. Drag and drop VariableBoolObject to LettoreVariabile's classeVariabile area in the inspector.

    • You can access the bool variable of other object with this way.

I hope this is the answer you search. Have a nice day.


 public class LettoreVariabile : MonoBehaviour
 {
     public VariabileBool classeVariabile;

     void Update()
     {
         Debug.Log(classeVariabile. variabile);
     }
 }