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];
Serlite
  • 12,130
  • 5
  • 38
  • 49
  • Possible duplicate of [downcast and upcast](http://stackoverflow.com/questions/1524197/downcast-and-upcast) – rutter Oct 23 '15 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 Oct 23 '15 at 16:23

1 Answers1

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.

Community
  • 1
  • 1
Serlite
  • 12,130
  • 5
  • 38
  • 49
  • 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 Oct 24 '15 at 20:02