How to reach variables in other functions?

    void Update () {
        GameObject[] InventoryButton;
        TakeObject ();
        DropObject ();
    }
    void GUIVisual()
    {

    }
    void OnGUI()
    {
        GUI.Box(new Rect(10, 10, 100,Screen.height - 20), "Menu");
        GUI.Box (new Rect (115, 10, Screen.width - 135, Screen.height - 20),"Inventory");

        for (int i = 0; i <= InventoryButton.length; i++) {
            GUI.Button (new Rect(10,25 + (10 * i),10,10), "Item : " + i);

        }

I do not understand why i can not use InventoryButton.length within the OnGUI function since i declared it in the update function.

I got the error message “the name does not exist in the current context” and nothing else.

Thanks in advice!

In C# you have to declare it as public. C# defaults to private if you don’t declare it as public or private and since you are declaring it within Update(), it cannot be called anywhere except within Update.

1 Like

Its all about scope (or context). A variable only exists until the closing } of the block (or scope) it was declared in.

So this will throw an error

void Update (){
    GameObject myObject = ...;
}

void SomeOtherMethod () {
    myObject...
}

But this code is valid

GameObject myObject;

void Update (){
    myObject = ...;
}

void SomeOtherMethod () {
    myObject...
}
1 Like

this is super basic stuff… I suggest doing some more tutorials from the learn section.

Thanks for all the answers i’ve not been writing any code for about a year or so. then i forgot some basic stuff.