Trouble adding game piece prefabs into an array.

Hi. Still learning and have come across an issue i cant find online or solve myself.

I’m working from a book called " Learning C# by developing game with unity 5.x."
I have started learning how to generate level pieces randomly to create an infinite side scrolling game.
After adding the code straight from the book, I believe i have created an array in which to store my level prefabs in unity. But when i select the array in unity I cannot add my level prefabs or anything into the array.
Have i messed up somewhere in the code?

public class LevelGenerator : MonoBehaviour {

   // added to any script we want accessed from another scripts
    public static LevelGenerator instance; 
    public List<LevelPiece> levelPrefabs = new List<LevelPiece>(); // creates a list of level peieces in the prefab, dont not change through the game
    public Transform levelStartPoint; // creates the position for the level starting point
    public List<LevelPiece> pieces = new List<LevelPiece>(); // creates a list of level peieces that will change depnding on what random peices appear


    private void Awake()
    {
        instance = this; // This scripts can be accessed from other scripts on awake
    }


    public void AddPiece()
    {
        int randomIndex = Random.Range(0, levelPrefabs.Count);// Code to pick a random number

        LevelPiece piece = (LevelPiece)Instantiate(levelPrefabs[randomIndex]); // instantiates copy of random level prefab and store it in the piece variable
        piece.transform.SetParent(this.transform, false);

        Vector3 spawnPosition = Vector3.zero;

        if(pieces.Count == 0)
        {
            spawnPosition = levelStartPoint.position;
        }
        else
        {
            spawnPosition = pieces[pieces.Count - 1].exitPoint.position;
        }

        piece.transform.position = spawnPosition;
        pieces.Add(piece);

    }
}

I tried to explain it the best i could, hope someone understands what i’m talking about

Thanks in advance.

Guy

If the pieces have a LevelPiece script on them, just drag n drop them into the script. You can drag them all at once, if you lock the inspector (little lock top right corner). You do not even need to set the size, as dragging them there will automatically give the size & add them.

Amazing, Thanks. I didn’t have the LevelPiece script attached to the Level Generator. Thanks again

Cool, glad you got it working :slight_smile: