- Home /
Getting a button to run a function
I'm having issues when I press the button.
I get: NullReferenceException: Object reference not set to an instance of an object
I also did try the same code below with:
void Start() {
Disks = FindObjectOfType(typeof(disks));
}
With that I got : Cannot implicitly convert type 'UnityEngine.Object' to 'disks'. An explicit conversion exists (are you missing a cast?)
using UnityEngine; using System.Collections;
public class battleGUI : MonoBehaviour { private disks Disks;
void OnGUI () {
if (GUI.Button(new Rect(10, 10, 150, 100), "Press to Rotate"))
{
Disks.SetMaxMin();
}
}
}
Thanks!
Answer by duck · Feb 19, 2010 at 05:15 PM
In general it's a good idea to adhere to Unity (and C#) coding conventions - your class name (and therefore your script name) should begin UpperCase, while member variables should be lowerCase. It's generally a good idea to stick to these, specially if you're posting code which you want others to be able to quickly understand and help with.
So, once you have renamed your script to "Disks", and the variable to "disks" (and battleGUI to BattleGUI!), perhaps your script should look something like this:
using UnityEngine; using System.Collections;
public class BattleGUI : MonoBehaviour { private Disks disks;
void Start() {
disks = (Disks) FindObjectOfType(typeof(Disks));
}
void OnGUI () {
if (GUI.Button(new Rect(10, 10, 150, 100), "Press to Rotate"))
{
disks.SetMaxMin();
}
}
}
In addition, in case you're not already aware of this, you can set up "dragged-references" in Unity. Have a look at my answer to this question for more information about creating drag and dropped references which is quite a cool feature of Unity's editor.