0

I am writing a game in Unity, and I am trying to use polymorphism to access 2 subclasses but keep getting an error:

Can not cast from source type to destination type

I have a serialized list of Places, and I am trying to downcast to a Property, which is a subclass of Place. How am I able to do this in Unity?

((Property)Board.GetBoardPlace(Players[PlayerTurn].Position)).Owner = Players[PlayerTurn];
2
  • Possible duplicate of downcast and upcast
    – rutter
    Commented Oct 23, 2015 at 16:06
  • For what you're doing in code, the cast is probably unnecessary. Can you share more of the code and/or reason for the cast? Also, this isn't really a Unity question, so I'm going to remove that tag and tag it C# instead...
    – Dan Puzey
    Commented Oct 23, 2015 at 16:23

1 Answer 1

0

If the items in your list of type Place were originally instantiated using the base type Place, then I don't think you can/should downcast (or rather, do type conversion) in this manner, at least not in a managed language like C#. Consider redesigning, or instantiate as items as type Property when populating your list:

List<Place> Places = new List<Place>();
Places.Add(new Property());

Then later, you can cast them to type Property when you need to use them:

Property property = Places[0] as Property;
if (property != null){
    // Conversion successful
}

You can read a bit more on this in this Stack Overflow question. Hope this helps! Let me know if you have any questions.

1
  • The problem is that the items are Dropped in the editor. Although the items are of type Property, there is no place in the code where I instantiate them. If it was done int he code using ... new Property() i think I would be fine but since I am trying to drop a dynamic board from the editor there is no way to do that. I thought dragging a Property type in the editor would be equivalent but it is not.
    – Celestrial
    Commented Oct 24, 2015 at 20:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.