Instatiate UI Button In Panel

I tried finding a similar post but they tend to be about what the button does when clicked.
So how do I instantiate a button on start?

This is what I got so far and I thought it would be correct, but clearly something is wrong because I get a null ref at this line; GameObject orb = GameObject.Instantiate(orbScript.buttonPrefab, Vector3.zero, Quaternion.identity, GameObject.FindGameObjectWithTag("GameWindowPanel").transform);

Here are the relevant script parts.

public class OrbSpawner : MonoBehaviour
{
    private ListScript listScript;
    private int orbAmount;
    private Orb orbScript;

private void Awake()
    {
        listScript = GetComponent<ListScript>();
    }

void Start()
    {
        orbAmount = listScript.x;

        foreach (int value in listScript.currentIntList)
        {
            GameObject orb = GameObject.Instantiate(orbScript.buttonPrefab, Vector3.zero, Quaternion.identity, GameObject.FindGameObjectWithTag("GameWindowPanel").transform);
            TextMesh textMesh = orb.gameObject.GetComponentInChildren<TextMesh>();
            int text = (value);
            textMesh.text = text.ToString();
            //
            orb.transform.position = new Vector3(Random.Range(720, 770), Random.Range(400, 480), 0);
        }
    }
}

The panel is tagged with the tag GameWindowPanel, there is a button prefab selected in the inspector for the buttonPrefab reference.

The listScript.x = orbAmount is a random number between 5 and 25, and is generated.
listScript.currentIntList is just the list of numbers above since the 5 to 25 numbers are random, and is the value I want to display on the buttons this should instantiate, but well yeah it doesn’t instantaite, just null ref.

Try setting the parent this way

GameObject item_holder = GameObject.FindGameObjectWithTag("GameWindowPanel");
GameObject orb = Instantiate (orbScript.buttonPrefab, item_holder.transform);
orb.transform.SetParent (item_holder.transform);

Hello there,

First, make sure your code is actually finding the tagged panel. Also, remember that it won’t find it if your panel is inactive at the time.

Another thing that might be null would be the orbScript variable, or its buttonPrefab variable.

It might sound silly, but never hesitate to do simple debugging to make sure you have everything setup right. If any of those lines below breaks, you’ll know where the error is.

Debug.Log("OrbScript: " + orbScript.gameObject.name);

Debug.Log("OrbScript Prefab: " + orbScript.buttonPrefab.name);

GameObject panel = GameObject.FindGameObjectWithTag("GameWindowPanel");
Debug.Log("Game Window Panel: " + panel.name);

I hope that helps!

Cheers,

~LegendBacon