C# how to modify a List<class>
I'm making a console RPG and am fairly new to generics. My problem is that I want a hero (stored in a hero List generic) to attack a monster (stored in an enemy List generic). The issue that I have is making the hero select a target from my monster generic, then modifying the monster's hpcurrent. This is easy with one monster and hero, but as I expand the game I intend to have several types of monsters and hero's; therefore I want to use a piece of code for my hero's which can pick out an item from a generic and modifying it's stats. The reason why there are two generics is because it makes it easier for me to see if all heroes or monsters are dead.
I will post the code for the monster ( it is identical to the hero's, the numbers are just different):
class Orc : Character
{
public Orc()
开发者_如何转开发 {
this.hpcurrent = 12;
this.hpmax = 12;
this.mpcurrent = 0;
this.mpmax = 0;
this.strength = 6;
this.defense = 4;
this.magicstrength = 0;
this.magicdefense = 2;
this.agility = 4;
this.level = 3;
this.isaliveBool = true;
this.name = "Orc";
this.weakness1 = "fire";
this.weakness2 = "thunder";
this.battlemove = null;
this.typeofcharacter = "monster";
}
The code for the List of monster's is:
public List<Character> enemies()
{
List<Character> enemies = new List<Character>();
enemies.Clear();
enemies.Add(new Orc());
return enemies;
}
you can use something like this:
public List<Character> Enemies
{
if (_Enemies == null)
{
_Enemies = new List<Character>();
_Enemies.Clear();
_Enemies.Add(new Orc());
}
return _Enemies;
}
private List<Character> _Enemies;
Then you can use like so:
obj.Enemies[0].HP += 25;
You'll need to add an identifier property to your Character
class in order to identify a specific enemy object and perform some action on it. The Guid
class works well for this purpose.
Really not sure what you're trying to accomplish, but classes are reference types in C#. That means if you modify the same enemy object outside of the collection, that change is reflected inside the collection as well. What's not clear is how you plan to use this. What object owns your list of enemies? How do you plant to retrieve a certain enemy from the list? Once you have the enemy you want from the list, updates are trivial.
精彩评论