Hi everyone. I am creating a game and I am pretty much done. This game is for a class though and I just realized that I need to add some Polymorphism to this game. I have already created a way to make levels random, so I could probably do it in a similar way, but I need to use Polymorphism. I know how to do this in JAVA, but not in C#/Unity. Do I need to create a separate class for each enemy? Anyone familiar with this? if so, could you push me in the right direction?
//Should I do something like this?
void Start () {
//Should I do this with every enemy
Enemy myEnemy = new devil();
Devil myDevil = (Devil)myEnemy;
//myDevil is just a placeholder, I would make a randomizer variable and stick it in there.
Instantiate (myDevil, EnemySpawner.transform.position, EnemySpawner.transform.rotation);
}
Basic polymorphism is pretty easy. Just make your enemies derive from a base class called “Enemy”.
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
using UnityEngine;
using System.Collections;
public class Devil : Enemy {
}
I can certainly do a bit more for you after I finish up my dinner. It’s quarter past five here on the west coast and I’m starving. If nobody beats me to it I should have a little something for you in an hour
Hopefully this will clear things up a bit more for you:
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public virtual void Attack() {
//Let's say every enemy can do a melee attack; so in here we would code up our melee attack.
}
}
using UnityEngine;
using System.Collections;
public class Devil : Enemy {
public override void Attack() {
//Let's say that devils have a ranged fire attack; we use this override void to call that attack instead of the attack method from the base class.
//This method overrides the base melee attack and replaces it with a fireball or something
//This is basic polymorphism. Classes that inherit from one another, but can have different results when calling the same method
}
}
This is a very good idea. I used this for part of my game where parts of the players body had to show up and disappear. I didn’t think about using that here until now. Thank you!!