Skip to main content

I'mI am trying to create ana MessageBox in Unity, but I'm having some troubles in c#C#.. This is my code (I'll explain my problem later):

I'm trying to create an MessageBox in Unity, but I'm having some troubles in c#.. This is my code (I'll explain my problem later):

I am trying to create a MessageBox in Unity, but I'm having some troubles in C#.. This is my code (I'll explain my problem later):

Source Link

Check if GameComponent is ready in Unity?

I'm trying to create an MessageBox in Unity, but I'm having some troubles in c#.. This is my code (I'll explain my problem later):

MsgBox.cs

public class MsgBox : MonoBehaviour
{
    private UIButton _btn_ok;  // NGUI Button
    private UILabel _caption;  // NGUI Label
    private GameObject _box;   // The message box container

    void Start()
    {
        _box = this.gameObject;
        _btn_ok = _box.transform.Find("btn_ok").GetComponent<UIButton>();
        _caption = _box.transform.Find("Title").GetComponent<UILabel>();

        // ** the line below works fine, but I don't want to change the caption here **

        // this.Caption = "This Works";
    }

    public string Caption
    {
        get
        {
            return _caption.text;
        }

        set
        {
            _caption.text = value;
        }
    }
}

My Saved Prefab Unity MessageBox

As you can see, my prefab have the MsgBox.cs attached to the Box component (wich is the _box variable).

But this code doesn't work:

Fail Code

function createBox()
{
    GameObject wnd = (GameObject)Instantiate(Resources.Load("Box"));
    MsgBox mb = wnd.GetComponent<MsgBox>();
    bool foo = true;

    if (mb == null)
    {
        Debug.Log("MsgBox is null");
        foo = false;
    }

    if (!(mb is MsgBox))
    {
        Debug.Log("mb is not MsgBox");
        foo = false;
    }

    if (foo)
    {
        Debug.Log("passed!");
        mb.Caption = "Hello!";
    }
}

Console Output

passed!
NullReferenceException: Object reference not set to an instance of an object MsgBox.set_Caption (System.String value) (at Assets/scripts/MsgBox.cs)

If I change this:

public string Caption
{
    get
    {
        return _caption.text;
    }

    set
    {
        _caption.text = value;
    }
}

to this:

public string Caption
{
    get
    {
        return _caption.text;
    }

    set
    {
        if (_caption == null)
            Debug.Log("Caption is null");
        else
            _caption.text = value;
    }
}

and call createBox, the console give me this:

Caption is null

Why? Why I can't change the caption from outside the MsgBox? Maybe the createBox() is being called first than Start()?

PS. Using Unity 5 64 bit. My platform is WebGL.
PS². English is not my native language, sorry.