- Home /
Simple Question: Animations and Base Class
Hello. Just a simple question: Is it possible to work with animations inside of abstract class?
Lets say I have:
public abstract class Enemy {
private AnimationClip _attackAnimation;
public virtual void Attack() {
// and now I want do do something like this:
GetComponent<Animation>().CrossFade(_attackAnimation.name);
}
}
Thanks for any help.
Why you are making abstract class? As we know we can not make object/instantiate abstract class. If you want to call this method you must override it in its sub-class/child class.
Thats right. I don't want to instantiate enemy. I want to have orcs, spiders, skeletons etc. that will use enemy's methods. But all of these enemies will have animation called "attack1". And thats why i am asking whether there is a way to call this animation once - in the Attack() method inside of enemy class - so i dont have to override it everytime.
Answer by Baste · Jun 15, 2015 at 01:27 PM
Yes
You need to subclass your Enemy class to actually do anything with it, but this is exactly how you implement abstract classes.
Though, for that to work, your Enemy class has to inherit from MonoBehaviour, otherwise GetComponent doesn't exist.
So, every class that is derived from this base class must have it's own implementation, even though it will always be the same implementation? $$anonymous$$g. if this Attack() function will have in 90% cases the same body (just play Attack animation, nothing more), then there is still no way to write it once and override only if needed?
No, you use the implementation from the base class unless you overwrite it. If you have the code above, and this class:
public class SomeEnemy : Enemy { //NOTHING HERE }
that'll work.
Yes, I know how this works. But my question is whether there is a way to make method inside of abstract class that can play animation. Or somehow call animation component and tell it which animation should be played.
Yes, by having the abstract class inherit from $$anonymous$$onoBehaviour.
$$anonymous$$onoBehaviour is an abstract class, and abstract classes can inherit from other abstract classes.