- Home /
Running a method from a subclass?
I'm a new programmer working on a TCG. I've got a bunch of cards that inherit from a "Card" class. Here's an example, Fireball.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Fireball : Card {
void Awake(){
hand = GameObject.Find("Hand");
centerSlots = GameObject.Find("CenterSlots");
fireCost = 0;
frostCost = 0;
timer = 2;
sprite = gameObject.GetComponent<SpriteRenderer> ();
inHand = true;
}
void Effect(){
//effect of card
}
void OnMouseDown ()
{
if (Castable () && inHand) {
Cast ();
}
}
}
I put all of the methods that I thought all of the cards would use in the Card class, which has been working well. Each card needs to have a separate "Effect" method, which I planned to write in each individual card script. In the game, the cards will take a certain amount of time to take effect. To do this, I used a coroutine in the Card class.
protected void Cast (){
PayMana ();
RemoveFromHandList ();
MoveToCenterSlot ();
AddToCenterSlotsArray ();
RealignHand ();
inHand = false;
inPlay = true;
StartCoroutine (Timer());
}
protected IEnumerator Timer (){
while (timer > 0) {
timer--;
yield return new WaitForSeconds (1);
}
gameObject.Effect
Destroy (gameObject);
}
}
This gives me the error " Type UnityEngine.GameObject' does not contain a definition for
Effect' and no extension method Effect' of type
UnityEngine.GameObject' could be found. Are you missing an assembly reference?"
I can't reference Fireball in the inspector, because there's going to be lots of different cards as prefabs. I'm still getting used to all of the objects and classes stuff, so maybe I'm making a simple mistake. Anyone have an idea of how to go about this, or happen to notice a mistake I'm making elsewhere? Thanks!
Answer by CesarNascimento · Feb 22, 2017 at 12:09 PM
You can use Effect as an abstract method. In this case you'd first need to add "abstract" to your Card class, to make it look like this
public abstract class Card
then add this to Card
public abstract void Effect();
Now, on Fireball and any other card that you inherit from Card, add "override" just before the return value of the method, like this
public override void Effect()
and now, inside Timer you just need to call Effect(); and it'll run the right method.