Search Unity

onGui fires twice on "Return" in input field.

Discussion in 'Scripting' started by dansav, May 2, 2008.

  1. dansav

    dansav

    Joined:
    Sep 22, 2005
    Posts:
    510
    I get "running" and "ran" twice each in the DebugLog. Why is onGui firing the event twice?

    How do I get the MyFunction to only be called once?

    Thanks,

    Dan

    <<code below>>

    function OnGUI () {
    stringToEdit = GUI.TextField (Rect (10, 10, 400, 20), stringToEdit, 100);
    if (Input.GetKeyDown ("return")) {
    Debug.Log("running");
    MyFunction();
    }

    }

    function MyFunction(){

    Debug.Log("ran");

    }
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    OnGUI() can run multiple times per frame. You should use functions like Input.GetKeyDown in Update() instead.

    --Eric
     
  3. jeremyace

    jeremyace

    Joined:
    Oct 12, 2005
    Posts:
    1,661
    The GUI does a Layout pass, and a Repaint pass each frame.

    So it will always be called twice.

    Like Eric said, it's best to handle events and such outside of the OnGUI function, and just change the data that is fed to your GUI.

    -Jeremy