Null Reference Exception GUI.Button

Hi,

I just want to show a button in this class. THAT’s ALL.
However, I keep getting a weird error.

Here’s the button code

void Update()
{
    if (GUI.Button(new Rect(10, 10, 100, 100), "Lock Cube"))
        Debug.Log("Worked");
}

When I run the game, I get this error

NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUI.Button (Rect position, System.String text) (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUI.cs:381)
MyClass.Update () (at Assets/Scripts/MyClass.cs:33)

line 33 in MyClass is the “if (GUI.Button(new Rect(10, 10, 100, 100), “Lock Cube”))” line.

I hope someone can help me fix this. I’ve searched the answers, most of them were using objects they have’t initialized. But I didn’t use any objects in that line.

You need to move this piece of code to the OnGUI method.