- Home /
Show GUI on collision
Hi everyone, I have a simple script here I'm having a small problem with:
var showGUI = false;
var launcherUpgrade1 : Texture2D;
function OnTriggerEnter (col : Collider) {
if(col.name == "Player" && GUI.enabled == false) {
GUI.enabled = true;
}
if(GUI.enabled == true) {
OnGUI();
}
else if(GUI.enabled == false) {
return;
}
}
function OnGUI () {
GUI.Box (Rect (10,10,100,50), GUIContent("400", launcherUpgrade1));
}
So basically when the player collides with the gameobject this script is attached to I want it to show the GUI. However, the GUI is automatically being shown as soon as the game starts. How can I fix this?
Answer by Waz · Aug 14, 2011 at 12:24 AM
You misunderstand GUI.enabled. It's not for that. It's for "greying out" UI elements. Try this:
var showGUI = false;
var launcherUpgrade1 : Texture2D;
function OnTriggerEnter (col : Collider) {
if(col.name == "Player")
showGUI = true;
}
function OnGUI () {
if (showGUI) {
GUI.Box (Rect (10,10,100,50), GUIContent("400", launcherUpgrade1));
... rest of the GUI ...
}
}
Or, if you really do want it to grey out:
function OnGUI () {
GUI.enabled = showGUI;
GUI.Box (Rect (10,10,100,50), GUIContent("400", launcherUpgrade1));
}
Aha, now it makes sense. Thank you for clearing that up for me, it works perfectly now.
Answer by Ziad · Aug 14, 2011 at 12:27 AM
make a script and name it
GUIControllerScript.cs
using UnityEngine;
using System.Collections;
public class GUIControllerScript : MonoBehaviour {
public bool ShowGUI = false;
void Start ()
{
}
void Update ()
{
if (ShowGUI)
{
G_U_I.Instance.enabled = true;
}
if (!ShowGUI)
{
G_U_I.Instance.enabled = false;
}
}
void OnTriggerEnter(Collider col)
{
if (col.name == "Player")
{
ShowGUI = true;
}
}
}
and this one name it
G_U_I.cs
using UnityEngine;
using System.Collections;
public class G_U_I : MonoBehaviour { public static G_U_I Instance;
void Start ()
{
Instance = this;
}
void Update ()
{
}
void OnGUI()
{
//Put ur GUI Script here
}
}
Conceptually, this approach has the advantage that the OnGUI
call is avoided by disabling the object completely. Your actual implementation though does that at the expense of having another Update()
every frame, which negates that benefit. Conceptually though, it is correct.