Hi all, I’m still pretty new to programming.
In the example below, I have a base class called Entity, which is then inherited by 3 other classes, Knight, Goblin and Rock.
Then in another script, I have a ReduceHealth() method that takes in Entity as parameter. Now the issue I’m having is I’ll have to recast each Entity that gets passed into the method in order to access their Health variable, which in turn creates a lot of duplicate codes.
Health wasn’t declared in the base class because the Rock doesn’t need one.
Is there a way to use a generic code that lets me handle this more efficiently? (see example near end of code)
Thanks!
example code
using UnityEngine;
using System.Collections;
using System.Collections.Generic; // required for List
// Base class
public abstract class Entity
{
protected string id = "None";
// Accessor
public string ID { get; set;}
}
// Derived classes
public class Knight : Entity
{
protected int health;
// Constructor
public Knight()
{
this.ID = "Knight";
Health = 3;
}
// Accessor
public int Health { get; set; }
}
public class Goblin : Entity
{
protected int health;
// Constructor
public Goblin()
{
this.ID = "Goblin";
Health = 1;
}
// Accessor
public int Health { get; set; }
}
public class Rock : Entity
{
// I am a Rock. I can't die!
// Constructor
public Rock()
{
this.ID = "Rock";
}
}
// Code testing class
public class ClassTest : MonoBehaviour
{
public List<Entity> characterList = new List<Entity>();
void Start()
{
Entity knight = new Knight();
Entity goblin = new Goblin();
characterList.Add(knight);
characterList.Add(goblin);
for (int i = 0; i < characterList.Count; i++)
{
ReduceHealth(characterList[i]);
}
}
public void ReduceHealth(Entity who)
{
if (who is Knight)
{
// Recast it as Knight
Knight k = who as Knight;
k.Health--;
Debug.Log(k.ID + "'s HP: " + k.Health);
}
else if (who is Goblin)
{
// Recast it as Goblin
Goblin g = who as Goblin;
g.Health--;
Debug.Log(g.ID + "'s HP: " + g.Health);
}
// Generic code. How can I do this??
// if (who is Rock)
// return;
//
// who.Health--;
// Debug.Log(who.ID + "'s HP: " + who.Health);
}
}