[SOLVED] How do I save and use Objects after instantiate?

Hi! Im a beginner and have a question. I couldn’t find a similar question.

I want to spawn and use (transform position, the design…) buttons in an array. I use a prefab of the button and have everything linked correctly (the prefab is linked to the script as ButtonPrefab).

public class LevelManager : MonoBehaviour
{
    public int numButtons = 10;
    public GameObject ButtonPrefab;
    public Button[] ButtonMap;

    // Start is called before the first frame update
    void Start()
    {
        ButtonMap = new Button[numButtons];

        for (int i = 0; i < numButtons; i++)
        {
            ButtonMap _= Instantiate(ButtonPrefab, new Vector3(i * 30f, i * 10f, 0), Quaternion.identity).GetComponent<Button>();_

//ButtonMap_.GetComponent().anchorMax = new Vector2(i * 10f, i * 10f);
//ButtonMap.GetComponent().anchorMin = new Vector2(i * 10f, i * 10f);
//ButtonMap*.name = “Button” + i.ToString();*_

if (ButtonMap == null)
{
Debug.Log("2 I am null " + i.ToString());
}
}

}
Now I get null everytime, how do I do this correctly? Thanks in advance! :slight_smile:
SOLVED:
public class LevelManager : MonoBehaviour
{
public int numButtons = 10;
public GameObject ButtonPrefab;
public GameObject[] ButtonMap;

// Start is called before the first frame update
void Start()
{
ButtonMap = new GameObject[numButtons];

for (int i = 0; i < numButtons; i++)
{
ButtonMap = Instantiate(ButtonPrefab, new Vector3(i * 30f, i * 10f, 0), Quaternion.identity) as GameObject;

ButtonMap*.name = “Button” + i.ToString();*

//Debug
if (ButtonMap == null)
{
Debug.Log("2 I am null " + i.ToString());
}
}

}

It looks like you’re trying to instantiate some buttons and store them in an array, but the ButtonMap array is coming back null.

One problem I see is that you’re calling GetComponent() on the instantiated object, but it’s possible that the object you’re instantiating doesn’t have a Button component attached to it. You can verify this by checking if the ButtonMap object is null after the instantiation.
If the object doesn’t have a Button component attached, then you’ll need to either attach a Button component to the prefab, or use a different component in the GetComponent call.