Reputation: 31
I have Base class Room
public class Room
{
public int width;
public int height;
public int minX;
public int minY;
public Room(int width, int height, int minX, int minY)
{
this.width = width;
this.height = height;
this.minX = minX;
this.minY = minY;
}
public virtual void GenerateRoom()
{
}
}
There are two types of room ProcedualRoom
and PredefinedRoom
public class ProcedualRoom: Room
{
public ProcedualRoomData data;
}
public class PredefinedRoom: Room
{
public PredefinedRoomData data;
}
Both classes have their respective data which are different from each other ProcedualRoomData
and PredefinedRoomData
In some other class where I am loading all the rooms
ILoad[] objsToLoad = GetComponentsInChildren<ILoad>();
foreach (Room r in procedualDungeon.rooms)
{
foreach (ILoad obj in objsToLoad)
{
obj.Load(r);
}
}
When I load Room I have to do typecast like this
public void Load(Room room)
{
if (room is PredefinedRoom)
{
Load((room as PredefinedRoom).data);
}
else
{
ProcedualRoom pRoom = (room as ProcedualRoom);
Load(pRoom);
}
}
Is there any other method to avoid typecasting ?
Upvotes: 0
Views: 54
Reputation: 673
You can create a class RoomData and add a filed with this type in Room class. ProcedualRoomData and PredefinedRoomData will derive from RoomData
public class RoomData
{
...
}
public class ProcedualRoomData: RoomData {
...
}
public class PredefinedRoomData: RoomData {
...
}
public class Room
{
public RoomData data;
....
}
Upvotes: 1