Declaring/modifying lists at runtime

Hopefully I explain this clearly enough.

Intended behavior: A character moves from room to room, visiting random objects in the room. It never visits the same object twice and may return to previously visited rooms.

Possible solution: The room carries a list of objects within it, which it passes to the visiting character. The character creates its own list of objects for that room and removes objects as they are visited.

Problem: For this solution, I would need to be able to create a list for each room at runtime (the number of rooms/objects is undefined). Is it possible to create lists in this way?

I’m trying for a clean and simple solution that’s flexible enough to accommodate any number of rooms/objects. Other solutions for the behavior are welcome as well.

Thank you!

This depends a bit if you want to create the list of objects per room in the inspector in unity, or during runtime. I’ll explain how to do it when you create the object list in runtime and then explain what to change if you want to manually create the object list in the inspector.

You can start by creating a List of objects per room. First, reference the generic collections:

using System.Collections.Generic;

then, to your room class, add a new list of objects:

List<MyObject> roomObjects = new List<MyObject>();

next, in your Start() method of the room, fill the list with object

roomObjects = GenerateObjectList(this); // you have to implement GenerateObjectsList(Room room) to return a list of objects for the given room.

now, when the player enters the room, you will need to COPY the list, not just reference it, otherwise when you remove something from the player’s list it will also remove it from the room’s list.

private Dictionary<room, List<MyObject> playerRoomObjectList = new Dictionary<room, List<MyObject>(); // this will hold the list of objects in each room as the player sees them.

// when entering a room, check if the player already has the list of objects. If not, copy it from the room
void EnterRoom(Room room) {
    if (!playerRoomObjectList.containsKey(room)) {
        playerRoomObjectList[room] = new List<MyObject>(room.roomObjects);

There, now you have a list of objects per room in your player’s script, to reference a list of a specific room use playerRoomObjectList[room]. If you want to remove an object from a room list:

void VisitedObject(Room room, MyObject obj) {

Now, if you want to populate the object list per room in the inspector, simply have an array of objects per room instead of a list (since you define this in advance in the inspector, it is a constant array and not a changing list):

public MyObject[] roomObjects = new MyObject[1];

Then, in the inspector, you can change the size of the array per room, and drag and drop MyObject scripts into it. The rest of the code should work the same.