Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I extend a class from another script in c# Unity

Tags:

c#

unity3d

I'm trying to extend a base class on my player object.
player has damage script that looks like this

using UnityEngine;
using System.Collections;

public class Damage : MonoBehaviour 
{

    public int health = 100;

    public virtual void ReceiveDamage(int damageAmount)
    {
        Debug.Log ("Original");
    }
}

And then the same player has another script like this :

using UnityEngine;
using System.Collections;

public class playerDamage : Damage 
{
    public override void ReceiveDamage(int damageAmount)
    {
        Debug.Log ("Extended");     
    }
}

But when I call the script from a 3rd scrip on another object like this:

var damageScript = collision.gameObject.GetComponent<Damage>();
if( damageScript)
{
    damageScript.ReceiveDamage(damageAmount);
}

the only response to the log is "Original" Shouldn't the child be called and "Extended" written to the log?

like image 808
Early73 Avatar asked Oct 23 '14 03:10

Early73


1 Answers

There are several ways to do this. The easiest one is to SendMessage.

collision.gameObject.SendMessage("ReceiveDamage", damageAmount);

Whatever implementation of ReceivedDamage that the collision GameObject has, that will be the one that is called. This is awesome because you don't need to specify the type yourself nor use GetComponent.


Important Extra Information

In any implementation that you choose the key step is to make sure that the right script is attached to the collision.gameObject. If you attach both scripts then you are playing with fire.

To avoid playing with fire please make Damage an abstract class.

public abstract class Damage : MonoBehaviour 
{
    public int health = 100;

    public virtual void ReceiveDamage(int damageAmount)
    {
       Debug.Log ("Original");
    }
}

Abstract will give you the same functionality you want, except that Unity3d won't let you attach Damage to the GameObjects, which is good to avoid mistakes. You will always have the option to have the original ReceiveDamage and the choice to override it on future classes that inherit from Damage, like this:

public class Example : Damage
{
    // This one still has ReceiveDamage but it happens in the base class.
}

or

public class PlayerDamage : Damage 
{
    public override void ReceiveDamage(int damageAmount)
    {
       Debug.Log("Extended");
    }
}
like image 112
apxcode Avatar answered Oct 06 '22 02:10

apxcode