Spawning prefab to an array, but array is empty and prefab is just in hierarchy.

Thanks in advance for your help!

What I want to do is spawn a random foodPrefab when I press a button. That food prefab should then go in to the foodArray. I have 4 foodPrefabs referenced from the inspector. They spawn but the array is never populated(stays zero) unless I manually increase the number in the inspector.

I tried to search for other similar questions but none of the answers I found worked for my solution. If you can link me a answer or tell me what I’m doing wrong I would appreciate it. Thanks again!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnFood : MonoBehaviour
{

    [Header("Food Attributes")]
    public GameObject[] foodPrefabs;

    public GameObject[] foodArray;

    public int spawnedFood = 0;

    public Transform spawnPoint;   

    void GetSpawnPoint()
    {
        int randomSP = Random.Range(0, SpawnPoints.spawnpoints.Length);
        spawnPoint = SpawnPoints.spawnpoints[randomSP].transform;
    }
    //On Button Press
    public void SpawnRandomFood()
    {
         //Get somewhere to spawn the food
        GetSpawnPoint();
        //Select a random food
        int randomFood = Random.Range(0, foodPrefabs.Length);

        foodArray[spawnedFood] = Instantiate(foodPrefabs[randomFood], spawnPoint.position, spawnPoint.rotation) as GameObject;

        spawnedFood++;


    }

`

If the foodArray need not to be visible in the inspector and it shouldn’t have a fixed size you should use a list instead of an array. You have to declare a size for an array and they can’t increase dynamically and you don’t know how often the user will press the button. List’s can increase dynamically and the user can press the button as often as she likes.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnFood : MonoBehaviour
{

[Header("Food Attributes")]
public GameObject[] foodPrefabs;

public List<GameObject> foodList = new List<GameObject>();

public int spawnedFood = 0;

public Transform spawnPoint;

void GetSpawnPoint()
{
    int randomSP = Random.Range(0, SpawnPoints.spawnpoints.Length);
    spawnPoint = SpawnPoints.spawnpoints[randomSP].transform;
}
//On Button Press
public void SpawnRandomFood()
{
    //Get somewhere to spawn the food
    GetSpawnPoint();
    //Select a random food
    int randomFood = Random.Range(0, foodPrefabs.Length);

    foodList.Add(Instantiate(foodPrefabs[randomFood], spawnPoint.position, spawnPoint.rotation) as GameObject);

    spawnedFood++;
}