- Home /
How to set different methods for instances of object
Here's the thing. I'm doing spells for my game. There's general class Spell that contains all the propierties like Name, Damage etc. There's also a method Cast and I'd like to overwrite it while creating instances of Spell so I can get different result while calling Cast. What are my options?
Answer by b_chrome · Feb 19, 2014 at 04:01 PM
You have a couple of choices:
Derive a class from Spell for each of the subsequent spells you want to create and make them override the Cast method (which you mark as virtual in the Spell class).
public class Spell /* : ScriptableObject // if you want to make it available as an asset */ {
public string name;
public int level;
public virtual void Cast(Transform source, Transform target) {
}
}
public class FireBall : Spell {
public override void Cast(Transform source, Transform target) {
//Make a fire ball and fire it
}
}
You could also use a delegate to which you supply a function:
public class Spell : MonoBehaviour {
public System.Action<Transform, Transform> Cast = delegate {};
}
public class FireBall {
public void Initialize(Spell spell) {
spell.Cast = (source, target) =>{
//Cast your fireball
};
}
}
These are great concrete examples. The first one is what I was referring to above. The delegate approach is also totally valid, and is very similar to how virtual functions actually work. The first example may be slightly faster than the second, because delegates can be chanced at run time but virtual functions cannot.
Great. I'm actually trying the delegate method. There's one problem. When I try to define Cast method the way you used at this (I guess it's calledlambda expression). Compiler says that "not all code paths return a value". But this Action just takes one argument and shouldn't return anything (it's void).
You are using Action not Function right? An Action shouldn't need a return value - which line is it on?
Alright, my bad. I checked entire method and finally figured out that error came actually from the class instantiating new Spell. Problem solved. Thank you very much :]
Answer by MakeCodeNow · Feb 19, 2014 at 04:01 PM
This is a texbook case for subclassing/polymorphism/virtual functions.
Assuming you're working in C#, this doc should get you started.
PS - Once you have subclasses, you'll probably also want to make your Spell class abstract (so that it can't be instantiated) as well as the Cast function (to force all subclasses to implement a Cast).
Your answer
Follow this Question
Related Questions
Is every Script I drag on a Gameobject an instance? 1 Answer
How to call a new instance of a class in C# 1 Answer
help with creating a static Instance in javascript 2 Answers
How can I use method to return custom classes (Same Class Type),How to return classes in method 1 Answer
C# Inheritance, base class attributes, override and null object 1 Answer