Sincress
Sincress

Reputation: 117

Unity3D ignoring my boolean variable

I'm working on a project using Unity 4.6.1 and I'm experiencing a weird issue: I have a bool variable which is initially set to false, and I'm trying to set it to true in the Start() method. First of all, it happens that the function in the same script gets called before the Start() method from another script (which should not be happening?) and secondly, the line ready = true; in Start() seems to be having no effect. Here's the relevant code:

public int ready = 0;

    void Start()
    {
        texts = new List<string>(3);
        texts.Add("");
        texts.Add("");
        texts.Add("");
        text1.text = texts[0];
        text2.text = texts[1];
        text3.text = texts[2];
        Debug.Log("Setting ready to true");
        ready = true;
    }

    public void showText(string text)
    {
        Debug.Log("Ready=" + ready);
        if (!ready)
            return;        
        texts.Insert(2, texts[1]);
        texts.Insert(1, texts[0]);
        texts.Insert(0, text);
    }

The log output for a run is:

16:07:03.563: Setting ready to true
16:07:24.831: Ready=0

Why is this happening?!

Upvotes: 0

Views: 174

Answers (2)

Sincress
Sincress

Reputation: 117

Before posting the question I decided to try using an int variable instead of a boolean and I forgot the change it back, which is why the int declaration is a mistake in the question above. It seems the Start() or Awake() method was not called at all because I instantiated the class using the new operator. I made the class extend MonoBehaviour, inserted an empty GameObject as a parent for the Text objects and did the following:

GameObject canvas = GameObject.Find("canvas");
uiController = canvas.AddComponent<UIText>();

The code in Awake() was changed to:

GameObject canvas = GameObject.Find("canvas");
text1 = canvas.transform.FindChild("Text1").GetComponent<Text>();
text2 = canvas.transform.FindChild("Text2").GetComponent<Text>();
text3 = canvas.transform.FindChild("Text3").GetComponent<Text>();
texts = new List<string>(3);
texts.Add("");
texts.Add("");
texts.Add("");
text1.text = texts[0];
text2.text = texts[1];
text3.text = texts[2];

Upvotes: 0

Programmer
Programmer

Reputation: 125285

You made a simple mistake. You declared the ready variable as int instead of bool.

Change public int ready = 0;

to

public bool ready = false;

Also, since ready is public, make sure that it is not set to false in the Editor. If you are NOT sure about this, make ready a private variable. So, replace public with private. My first answer should solve your problem.

Upvotes: 3

Related Questions