Let me first try to explain what I’m trying to achieve.
I’m making a game where the player can pickup power-ups(which I called, for some reason, “Loot” in my game). So here’s a really basic form of my Loot class:
public class Loot : Sprite
{
//Properties and fields...
public Loot(/*parameters...*/)
{
}
public virtual OnPickUp(Player player)
{
}
}
Player and Sprite are classes from me. Here’s my problem: my sprite class holds a position(a Vector2, a struct from XNA representing a vector) and from my understanding of how C# works, copying two sprites will copy the reference of eachother, therefor, whenever I change one’s position, it will change the other one’s too.
Whenever a loot should spawn, I have a class holding the possible loots that can spawn which returns a random one and the loot is copied and shown to the screen, but as soon as I get more than one of the same type of loot, it messes up because of the reference copy problem (both will share the same position and only one will be visible).
So then I tried creating a new Loot object whenever I needed to spawn a new loot, so I had to provide a constructor with multiple parameters to easily copy a loot this way:
(Let’s pretend toSpawn can be any type derived from the Loot class, like a HealthPack, or whatever)
Loot spawning = new Loot(toSpawn.Position, toSpawn.Color /*etc...*/);
It looked right until I decided to implement “OnPickUp”. Since I create a new Loot object rather than the proper child class, the functionality of toSpawn‘s OnPickUp function would disappear and picking up a loot would end up doing nothing(it would only call the base class Loot’s empty function).
Obviously, I am doing something wrong here. I don’t have much programming experience, and even less with C#, so I really have no idea of how I can fix this. I tried using an Action< Player> object representing the OnPickUp functionality, it would work but still limit me quite a lot(since I have to pass a static function as an Action< Player>, therefor limiting me to use the information of the player parameter and preventing me from using the sub-class specific information).
So, finally, my question really is: What would be a better design to allow having sub-classes with overloaded functions, but still being able to clone the base class and its properties?
Thank you for your precious time.
If anything is not clear enough(and I know it’s not), then just ask me in the comments and I’ll try to describe my problem in more details.
have your Loot class implement ICloneable