I am new to Unity and I am currently trying to add a Button dynamically to a Canvas in my scene. The button is a prefab called EventButton which I add as a public variable in my script:
But when I run the game, I can see that a clone of my button is added to the scene, but it’s not visible and I get the following error:
NullReferenceException: Object reference not set to an instance of an object
GameController.MakeButtons () (at Assets/Scripts/GameController.cs:25)
GameController.Start () (at Assets/Scripts/GameController.cs:17)
Now, I have a bachelor’s degree in Computer Science so I know what the above means. But I don’t know why it happens. Below is my script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GameController : MonoBehaviour
{
public Canvas canvas;
public Button buttonPrefab;
public float xMin;
public float xMax;
public float yMin;
public float yMax;
void Start ()
{
MakeButtons ();
}
void MakeButtons ()
{
for (int i = 0; i < 3; i++) {
Vector3 pos = new Vector3 (Random.Range (xMin, xMax), Random.Range (xMin, xMax),0);
Button btn = Instantiate (buttonPrefab, pos, canvas.transform.rotation) as Button;
btn.GetComponent<Text>().text = "" + (i + 1);
RectTransform rect = btn.GetComponent<RectTransform>();
rect.SetParent(canvas.transform, false);
rect.offsetMin = Vector2.zero;
rect.offsetMax = Vector2.zero;
}
}
}
I would really appreciate some help with this, as Unity is rather tricky at first glance for me.