Method not found: GUI.Button

I try to play around with UnityGui a bit, and tried the example from the reference Guide. However when I implement an OnGUI() Method, only the above error is displayed.
What am I doing wrong? Do I have to import/include something first?

This is my sample code:

// Draws 2 buttons, one with an image, and other with a text
// And print a message when they got clicked.
var btnTexture : Texture;
function OnGUI() {
    /*
    if (!btnTexture) {
        Debug.LogError("Please assign a texture on the inspector");
        return;
    }*/
    if (GUI.Button(Rect(10,10,50,50),btnTexture))
        Debug.Log("Clicked the button with an image");
     

    if (GUI.Button(Rect(10,30,50,50),"Click"))
        Debug.Log("Clicked the button with text");
}

This is attached to an empty Game-Object that I created just to get a GUI.

There's nothing wrong with your script but I couldn't tell you what the problem is. You could try reinstalling Unity which might work if there's a problem with the Unity libraries.

2 Answers

2

You probably named your filename GUI.js, causing your new GUI type to conflict with the existing GUI type. Either rename your file or make an explicit call to UnityEngine.GUI.

If I were you, I would rename the file to GUIExample or something.

// Draws 2 buttons, one with an image, and other with a text
// And print a message when they got clicked.
var btnTexture : Texture;
function OnGUI() {
    /*
    if (!btnTexture) {
        Debug.LogError("Please assign a texture on the inspector");
        return;
    }*/
    if (UnityEngine.GUI.Button(Rect(10,10,50,50),btnTexture))
        Debug.Log("Clicked the button with an image");


    if (UnityEngine.GUI.Button(Rect(10,30,50,50),"Click"))
        Debug.Log("Clicked the button with text");
}

Thank you very much, that did the trick! So do I understand it right, that I can access methods from other files by using the filename as objectname? Where can I find more information about this topic?

In Unity javascript files are treated like classes so a file named MyGUI.js can be used like a class MyGUI which inherits from MonoBehaviour. Any classes you define (properly) in your Assets folder are available in any scripts.

I don't see anything wrong with the syntax, and more importantly I just copy/pasted your script into a new Javascript and it worked fine.

The only thing I can think of is that the name you gave the script might be a problem. Make sure not to name the script GUI or Button or any existing class. I would delete your script, make a new one, name it something unique ("MyGUI") and paste the above code into it.

Also, be careful not to rename a script in Unity while the script is open in an editor, that can cause strange results. It may also help to close Unity and any editor and then open up again to clear things out.

Edit: Oops, someone beat me to it, same conclusion though. :)