Reputation: 56
Assuming that doing typecasting isn't viable for performance reasons:
public class ai_task
{
public virtual TaskStatus StartTask(Base_NPC mRef) { return TaskStatus.STARTED; }
public virtual TaskStatus RunTask(Base_NPC mRef) { return TaskStatus.RUNNING; }
public virtual void EndTask(Base_NPC mRef) { }
}
Say we have this base class for all NPCs and we want to get around to making different tasks for different types of NPCs.
This is what I have:
public class Shoot_Target : ai_task
{
public TaskStatus StartTask(Shooter_NPC mRef)
{
//Shoot target, pew pew
return base.StartTask(mRef);
}
}
Is this the best way to go about handling it?
And if not, what is the best approach?
Keep in mind the functions are virtual in ai_task because I may want to create generic tasks that can be applied to all NPCs.
Upvotes: 1
Views: 398
Reputation: 56
Turns out generics were the answer.
Here is a test snippet that I put in another program:
//Parent class
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal, I don't speak");
}
}
//Child class
public class Human : Animal
{
public override void Speak()
{
Console.WriteLine("I'm a more evolved animal. I DO speak.");
}
public void InventStuff()
{
Console.WriteLine("And also as a human I can do things like invent tools.");
}
}
public enum TaskStatus
{
STARTED = 0,
RUNNING,
COMPLETE,
FAIL
}
public class ai_task<T>
{
public virtual TaskStatus StartTask(T mRef) { return TaskStatus.STARTED; }
}
public class Speak_Task : ai_task<Animal>
{
public override TaskStatus StartTask(Animal mRef)
{
mRef.Speak();
return base.StartTask(mRef);
}
}
public class Invent_Task : ai_task<Human>
{
public override TaskStatus StartTask(Human mRef)
{
mRef.InventStuff();
return base.StartTask(mRef);
}
}
Below snippet for output:
var man = new Human();
var dog = new Animal();
var spktask = new Speak_Task();
var invtask = new Invent_Task();
Console.WriteLine(spktask.StartTask(man));
Console.WriteLine(spktask.StartTask(dog));
Console.WriteLine(invtask.StartTask(man));
Upvotes: 1