So I want to spawn in a random enemy from a List of enemies, but I can’t find a clean way to create a new Enemy instance from the Enemy instance in the list. This is mainly because I have enemies of different object types (subclasses of type Enemy) entirely, so I can’t simply copy all the attributes over.
For example:
List<Enemy> EnemyDB = new List<Enemy>();
EnemyDB.Add(new Enemy(150,1.8f,"grunt"));
EnemyDB.Add(new EnemyOther(60, 5.8f, "bug"));
Enemy template = EnemyDB.[get random enemy];
Enemy toBeSpawned = ????;
How can I get a new instance of the list’s enemy? Is there a better way entirely to do this?
Try creating a “Clone” method on each Enemy subtype and call that method on the one you choose randomly from the List. You could also go “flyweight”; create a shallower copy that simply references the Enemy’s more expensive members, like graphical elements (sprites, textures, skeleton), instead of making multiple in-memory copies.