Using a subclass in the inspector in place of a parent class and accessing the subclass variables
Hello everyone, I would like you to help me on an inheritance problem in Unity. I have two classes : Room, inheriting from ScriptableObject
public class Room : ScriptableObject
{
public string roomName;
public GameObject building;
}
And Classroom, inheriting from Room :
public class Classroom : Room
{
public List<Teacher> teacherList;
public List<Student> studentList;
}
Both are ScriptableObjects if it matters.
I made a menu for the player to choose among all the rooms (i.e classrooms + other future Subclasses of room).
When a room is choosen in this menu, its building (GameObject) is instantiated. Regardless of what Subclass of Room is choosen, a roomController (A script to manage the room) is attached to this GameObejct. This controller is expecting a Room variable which is send by the script of the menu.
Hence, when I create a Classroom, this can be found in the inspector of the building instantiated :
You can see here that the Unity inspector accept a Classroom variable in place of a Room variable (but I wasn't surprised since one is a subclass of the other). But in my roomController, I cannot access any of a Classroom variables when I'm using the variable room on the grounds that this variable is a Room type (the expected type by Unity's inspector) and not a Classroom type (which is really is).
I add that when i'm using a GetType() on the room variable I get a "Classroom" on the console.
Is there a way to convert this room variable from Room type to Classroom type ?
Thank you in advance.
Answer by quilamaguery · Jun 02, 2020 at 05:50 AM
I come back with a temporary fix.
Since the roomControlled receive a Classroom instance we can use a as-cast like this :
classroom = room as Classroom;
Then you can exploit the Classroom instance in the roomController.
I don't recommend the use of an as-cast in general though since it can lead to errors if the Classroom element you're supposed to receive is not a Classroom type finaly.