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) {
playerRoomObjectList[room].remove(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.