So, there are many examples in the scripting guide about unityGUI.
But where exactly do I put the OnGUI function?
on a MonoBehavior class extend in C# or anywhere in javascript.
The important point is that it must be on a component that is assigned to an object in your scene
When I put OnGUI in a javascript, unity says “Button is not a member of GUI” (same with box etc, there seems to be something wrong in recognizing GUI in my js)
So I can attach the OnGUI-script to an empty gameobject. Or wich method is most commonly used?
Do you have a script in your project named “GUI”?
The script was named ‘GUI’ I changed the name and it’s working now.
Thanks!
Hi Spiky,
do following steps.
- create a empty javascript or c# file.
- rename it to mygui.js (for Javascript) or mygui.cs (for c#)
- open the file with unitron or other text editor
- use this code
Javascript
function OnGUI(){
GUI.Button(Rect(10,10,100,25), "Click me");
}
c#
using System.Collections;
using UnityEngine;
public class mygui : MonoBehaviour{
void OnGUI(){
GUI.Button(new Rect(10,10,100,25), "Click me");
}
}
- Attach the script mygui.js or mygui.cs to your Main Camera or any other object in your hierarchy view.
i hope that helps
Just so you have the “why is that?” information. When you named your script GUI you confused our script engine, and so attempts to call GUI.Button() result in the script engine looking for a function named Button() inside of your script, which it likely didn’t have. Thus the solution is to avoid such name collisions and use a file name other than GUI.js as you’ve now done.
Carry on!