How to have OnGUI element in a OnTriggerEnter function?

Hi, how can i to have GUI functions inside a OntriggerEnter function? because we cant put a function inside a function…please help on what other approach…thanks

3 Answers

3

You can’t. You must use a boolean variable to enable GUI functions and set/reset it at OnTrigger, like this:

EDITED: As I told, you can’t put OnGUI inside OnTriggerEnter - you must create your GUI code inside a regular OnGUI function, and use a boolean variable to enable your GUI code; set or clear this variable at OnTriggerEnter/OnTriggerExit, and you will get the same effects as if the GUI code were inside OnTrigger:

 
var guiEnable = false; // variable which controls GUI

function OnGUI(){
  if (guiEnable){
    // your GUI code goes here
  }
}

function OnTriggerEnter (myTrigger : Collider) { 
  if (myTrigger.name == "user") guiEnable = true; // enable gui code on trigger enter
}

function OnTriggerExit (myTrigger : Collider) {
  if (myTrigger.name == "user") guiEnable = false; // disable gui code on trigger exit
}

But you can't place GUI functions inside OnTrigger: take a look at my answer (I edited it to adapt to your code). The GUI functions are actually placed inside the OnGUI function, but only execute if the variable guiEnabled is true - and this variable is set/reset in OnTrigger events.

Sorry for being too late, but how did you get it to work? I am facing the same issue. Even after correcting the code, it wont work. :(

This should be your solution;

function OnTriggerEnter(collision : Collider)
{
 if (collision.tag == "Player")
 {
 sart = true;
 Application.LoadLevel("///////////");
 }
}


function OnGUI()
{
    if(sart)
    {
        GUI.BeginGroup(new Rect(Screen.width/2+450, Screen.height - 100,290,90), "");
 GUI.Box(new Rect(10,40,200,40), "");
 //////////////////////////////////
 GUI.EndGroup();
    }
}

I have something like that `using UnityEngine;
using System.Collections;

public class RenderinGUI : MonoBehaviour {
public GUITexture texture;
public GUIText text;
bool on = false;
void Start(){
text.enabled = false;
texture.enabled = false;
}
void OnTriggerEnter(Collider col){
if (col.tag == “Player”) {
on = true;
}
}
void OnGUI(){
if (on == true) {
text.enabled = true;
if (Input.GetKey (KeyCode.E)) {
text.enabled = false;
texture.enabled = true;
}
if (Input.GetKeyUp (KeyCode.E)) {
text.enabled = true;
texture.enabled = false;
}
}
}
}
`