Search Unity

Where to put OnGUI function?

Discussion in 'Immediate Mode GUI (IMGUI)' started by SPIKY, Jan 5, 2009.

  1. SPIKY

    SPIKY

    Joined:
    Dec 19, 2008
    Posts:
    57
    So, there are many examples in the scripting guide about unityGUI.
    But where exactly do I put the OnGUI function?
     
  2. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    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
     
  3. SPIKY

    SPIKY

    Joined:
    Dec 19, 2008
    Posts:
    57
    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?
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Do you have a script in your project named "GUI"?
     
  5. SPIKY

    SPIKY

    Joined:
    Dec 19, 2008
    Posts:
    57
    The script was named 'GUI' :) I changed the name and it's working now.
    Thanks!
     
  6. LDiederich

    LDiederich

    Joined:
    Jan 5, 2009
    Posts:
    15
    Hi Spiky,

    do following steps.

    1. create a empty javascript or c# file.
    2. rename it to mygui.js (for Javascript) or mygui.cs (for c#)
    3. open the file with unitron or other text editor
    4. use this code

    Javascript
    Code (csharp):
    1.  
    2. function OnGUI(){
    3.    GUI.Button(Rect(10,10,100,25), "Click me");
    4. }
    5.  
    c#
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using UnityEngine;
    4.  
    5. public class mygui : MonoBehaviour{
    6.  
    7.    void OnGUI(){
    8.        GUI.Button(new Rect(10,10,100,25), "Click me");
    9.    }
    10. }
    11.  
    5. Attach the script mygui.js or mygui.cs to your Main Camera or any other object in your hierarchy view.


    i hope that helps
     
  7. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    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!
     
    BJosephine likes this.