This is a simple problem but I can’t figure it out. I’ve declared a public variable in the class definition:
public GameObject cube;
I have then created a test prefab which contains a sphere, and dragged it onto this public variable in the editor. Then back in my script I attampt to instantiate when a button is pressed:
Instantiate(cube,new Vector3(0,0,0),Quaternion.identity);
But I always get the error:
NullReferenceException: The prefab you want to instantiate is null.
I’m going to insert the whole class underneath here in case its something else thats messing things up.
using UnityEngine;
using System.Collections;
public class GuiBehaviour : MonoBehaviour
{
// define and create our GUI delegate
private delegate void GUIMethod();
private GUIMethod currentGUIMethod;
private int length = 10;
private int buttonHeight = 30;
private int spacer = 2;
//public TopTweetController gameController;
public GameObject cube;
void Start ()
{
// start with the main menu GUI
this.currentGUIMethod = MainMenu;
iPhoneSettings.screenOrientation = iPhoneScreenOrientation.Portrait;
}
public void MainMenu()
{
// Make a background box
GUI.Box (new Rect (10,10,300,460), "Main Menu");
GUI.Label(new Rect(20,350,300,40),"Test String");
for(int i=0;i<length;i++)
{
if(GUI.Button (new Rect (20,(spacer*i)+(buttonHeight*i)+30,280,30), "Game "+i.ToString()))
{
this.currentGUIMethod = threeDView;
}
}
if (GUI.Button (new Rect (20,Screen.height-70,280,30), "Options"))
{
// options button clicked, switch to new menu
this.currentGUIMethod = OptionsMenu;
}
}
private void OptionsMenu()
{
// Make a background box
GUI.Box (new Rect (10,10,300,460), "Options Menu");
GUI.Label(new Rect(20,350,300,40),"Test String");
if (GUI.Button (new Rect (20,Screen.height-70,280,30), "Main Menu"))
{
// go back to the main menu
this.currentGUIMethod = MainMenu;
}
}
private void threeDView()
{
GUI.Box (new Rect (10,10,300,460), "3D View");
GUI.Label(new Rect(20,350,300,40),"Test String");
if (GUI.Button (new Rect (20,Screen.height-70,280,30), "Main Menu"))
{
// go back to the main menu
this.currentGUIMethod = MainMenu;
}
Instantiate(cube,new Vector3(0,0,0),Quaternion.identity);
}
// Update is called once per frame
public void OnGUI ()
{
this.currentGUIMethod();
}
}