Returning an upcasted type to it's original type without knowing what it is
I'm writing some code to create buttons that will allow the player to build some in game objects. Each gameobject starts as s Scriptable Object, which contains the gameobject's base stats and a prefab. During initialization the Scriptable Objects are created by deserializing some JSON, following this they are added to a List.
The Scriptable Objects all derive from the same base Class "RoomTemplate" but there are many child classes such as LoungeTemplate and KitchenTemplate. All of this works just fine.
The problems start when I try to create the GameObjects. I populate a scroll rect with buttons by iterating through the List and when I click them it just runs the Create method in the parent room template object. I understand that this is because by placing them in the list I have Upcasted them but since they're created by iteration I can't think of a good way to Downcast them with resorting to a long list of if statements or a switch statement that identifies the upcasted class and downcasts it to the correct one.
Can anyone help?
Answer by Cynicide · Apr 27, 2016 at 03:05 AM
Answering my own question here. You don't need to downcast the object. You just need to make sure that the base class has the method defined as a virtual and subsequent child classes have it defined as a override. See here with the Create() method.
// Template Class
[CreateAssetMenu(fileName = "BaseRoom.asset", menuName = "BaseRoomTemplate")]
public class BaseRoom : ScriptableObject
{
public int RoomID = 0;
public string RoomName = null;
public string RoomDesc = null;
public virtual void Create()
{
// To be overidden
Debug.Log("Should Not See");
}
}
// Lounge
[CreateAssetMenu(fileName = "Loungeroom.asset", menuName = "LoungeroomTemplate")]
public class Loungeroom : BaseRoom
{
public int Comfort = 3;
public GameObject prefab;
public void Init(GameObject pf)
{
RoomID = 1;
RoomName = "Lounge";
RoomDesc = "The Lounge Room";
prefab = pf;
}
public override void Create()
{
Debug.Log("Creating Lounge");
GameObject newroom = Instantiate(prefab);
}
}
Your answer
Follow this Question
Related Questions
Making an image appear 0 Answers
Enemy Detection 1 Answer
help for C# ; when all were green 1 Answer
No lofor hacer un paso de escena en 2D 1 Answer
How do a script to make Combo atack/special moves like Castlevania 0 Answers