Create a list of buttons, and instantiate prefab when button is clicked

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 :slight_smile:

Thanks

Paul

Start by figuring out what is null. Do this through log statements or by attaching a debugger. Is it factoryBlocks? Is it blockPlacement?

Then you can figure out why it is null.

As always I should have started with the simple things first (which your reply prompted me to do!). Turns out blockPlacement was not attached…doh.

Thanks for the help :slight_smile: