I’ve got a GUI menu with a GUI button on it, when the button is pressed I want a GUI texture to come up which will display information. Ive got the following script but when I click the button, it doesn’t bring the texture up (I’ve assigned it in the Inspector):
using UnityEngine;
using System.Collections;
public class GUIDisplay : MonoBehaviour
{
public Texture2D background;
public Texture2D helpPage;
void OnGUI()
{
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),background);
GUI.backgroundColor = Color.clear;
if(GUI.Button(new Rect(Screen.width * (4.5f/6.55f),Screen.height * (5.25f/6.3f),Screen.width * (0.8f/6.55f), Screen.height * (0.85f/6.3f)),""))
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),helpPage);
}
}
Any ideas what I’m doing wrong?
Alternatively, I could activate and deactivate the texture, I tried:
helpPage.SetActive(true);
and
helpPage.enabled = true;
But neither of these worked. (I’m using C# by the way)
The problem is that the OnGUI method is called a lot. (depending on the event) OnGUI gets called once per frame for the Repaint event for instance. And whenever you mousedown, mouseup, mousemove etc. OnGUI will be called additional times for each event.
Your problem is that the content of the if(GUI.Button()) call only gets called on the mouseUP event. Not the repaint event. so any GUI calls inside are basically ignored.
So the thing you could do is something like the following
using UnityEngine;
using System.Collections;
public class GUIDisplay : MonoBehaviour
{
public Texture2D background;
public Texture2D helpPage;
private bool clicked = false;
void OnGUI()
{
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),background);
GUI.backgroundColor = Color.clear;
if(GUI.Button(new Rect(Screen.width * (4.5f/6.55f),Screen.height * (5.25f/6.3f),Screen.width * (0.8f/6.55f), Screen.height * (0.85f/6.3f)),""))
clicked = true;
if (clicked)
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),helpPage);
}
}
For more information about how OnGUI works you should check the docs.