Hello, I’m creating an array of buttons which, when clicked should instantiate a prefab, however I am getting a null reference exception when clicking the button, from line 23.
Here is the code that creates the buttons based on the provided prefabs:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LoadOut : MonoBehaviour
{
public GameObject[] factoryBlocks;
private BlockPlacement blockPlacement;
public Button buttonPrefab;
private void Start()
{
blockPlacement = GetComponent<BlockPlacement>();
for (int i = 0; i < factoryBlocks.Length; i++)
{
Button button = Instantiate(buttonPrefab, this.transform.position, this.transform.rotation);
button.transform.SetParent(this.transform);
button.image.sprite = factoryBlocks[i].GetComponent<BlockProperties>().thumbNail;
int tempVar = i;
button.onClick.AddListener(delegate { blockPlacement.SetBlock(factoryBlocks[tempVar]); });
Debug.Log("made button for " + factoryBlocks[tempVar]);
}
}
}
within another script (which does not get called as the debug is not triggered) is the following code to instantiate the prefab:-
public void SetBlock(GameObject b)
{
Debug.Log(b.name);
hasPlaced = false;
currentBlock = ((GameObject)Instantiate(b)).transform;
placeableBlock = currentBlock.GetComponent<PlaceableBlock>();
}
Any help would be much appreciated ![]()
Thanks
Paul