how do I extend a class from another script in c# Unity
Solution 1
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");
}
}
Solution 2
I think when you call this line:
var damageScript = collision.gameObject.GetComponent<Damage>();
It gets the component by name, which in this case would be the Damage script, not the playerDamage script.
In you script it should be:
var damageScript = collision.gameObject.GetComponent<playerDamage>();
if( damageScript)
{
damageScript.ReceiveDamage(damageAmount);
}
Early73
Updated on June 14, 2022Comments
-
Early73 almost 2 years
I'm trying to extend a base class on my player object.
player has damage script that looks like thisusing 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?