Calling a function in a parent script

Hi

I have several script which inherits from each other.
For example I have my “Unit” script which does some calculations,
and I have my… lets say “Tank” script, which inherits from Unit, the unit script calculates if an enemy is near the object, and if so, it should fire a bullet.
The real situation is a bit more complicated but the basic principle is the same.

So how can I call a function in the Tank script from the Unit script, also I don’t know the type of the script since I have several scripts inheriting from Unit (Tank, Infantery, Car, etc).
I know I can use SendMessage, although it takes to much power, I want to use a direct call, like myScript.Fire ()

PS: Can’t use dynamic typing since I’m using C#

Are you looking for something like this?

using UnityEngine;
using System.Collections;

public class Burnes : MonoBehaviour {

    public Unit myUnit;

    void Start() {
        if(myUnit is Tank)
            (myUnit as Tank).fire();
        else
            myUnit.fire();
    }
}


public class Unit {
    public virtual void fire() {
        Debug.Log("Fire from UNIT");
    }
}


public class Tank : Unit {
    public override void fire() {
        Debug.Log("Fire from TANK");
    }
}

Well, I can use “as Tank” since I don’t know if it is going to be a “Tank” script or a “Infantery” script or something else.
But thanks anyway!

EDIT: Or wait, can I use an if like that? "if(myUnit is Tank) " I though you needed to use GetType and weird stuff like that to do that.

Humm, try this, the output is:

Fire from UNIT.
Fire from TANK.
Fire from TANK.

You don’t need to know the childs type.

using UnityEngine;
using System.Collections;

public class TestIt : MonoBehaviour {

    public Unit myUnit;
    public Tank	myTank;

    void Start() {
    	myUnit = new Unit();
    	myTank = new Tank();

        myUnit.fire();
        (myTank as Unit).fire();
        myTank.fire();
    }
}


public class Unit {
    public virtual void fire() {
        Debug.Log("Fire from UNIT");
    }
}


public class Tank : Unit {
    public override void fire() {
        Debug.Log("Fire from TANK");
    }
}

Hi

I didn’t get it working until today (bit late maybe) when I tried to add those virtual and override tags, and now it works, THANK YOU SO MUCH!! :smile: