- Home /
Why won't my OnGUI() code work?
This is my code:
using UnityEngine;
using System.Collections;
public class ButtonScript : MonoBehaviour {
public Texture2D icon;
// Use this for initialization
void Start () {
}
void OnGUI()
{
if (GUI.Button (new Rect (25, 25, 25, 25), icon)) {
Application.LoadLevel ("LevelSelectScreen");
}
}
// Update is called once per frame
void Update () {
}
}
I have icon set as a texture but it won't show on my scene or on the game. Plus, I can't click on it. What is wrong with this code? I got it from: http://docs.unity3d.com/Manual/gui-Basics.html It might help to know that I changed my texture from a sprite to a texture in the inspector. Thank You!
Out of curiosity how can you not click on something that is not showing up?
You might also want to try changing your Rect to (25,25,0,0) and adding in the curly brackets.
Throw a debug.log into the OnGUI (outside the if) to see if the method is being called at all?
Answer by Detinator10 · Jul 06, 2014 at 09:31 PM
The problem was that i had the first two variables in the rect set to 25 which meant it was 25 times the camera height and width and when i changed that to .5 it worked. Here is my final code(the GUI.backgroundcolor = Color.Clear is to make the buttns invisible):
using UnityEngine;
using System.Collections;
public class ButtonScript : MonoBehaviour {
public Texture2D icon;
public float posX;
public float posY;
public string LevelToLoad;
// Use this for initialization
void Start () {
}
void OnGUI()
{
GUI.backgroundColor = Color.clear;
if (GUI.Button (new Rect (Screen.width * posX, Screen.height * posY, 200, 40), icon)) {
Application.LoadLevel (LevelToLoad);
}
}
// Update is called once per frame
void Update () {
}
}
Answer by Duss · Jul 01, 2014 at 04:08 AM
I tried your code and it works fine. Make sure that your ButtonScript is in the scene you are testing. Even if you don't have any texture attached to it, you should see the default GUI button at the top left corner.
Answer by Mehul-Rughani · Jul 01, 2014 at 04:08 AM
Make Sure That You Have Assigned a Script to any Object Because In The Script There is no problem at all.