Создать базовый класс
public abstract class Health : MonoBehaviour
{
// make a member e.g. protected so it is not public but still accesible by inherited classes
protected float health = 100f;
// Now you either can make the method abstract
// This means every inheritor later HAS to implement this method
public abstract void Die();
// or you can make it virtual
// This means this class already provides an implementation
// but an inheritor could
// a) simply use it
// b) extend it or
// c) completely overrule it
public virtual void TakeDamage()
{
Debug.Log("Ouch!");
health -= 1;
}
}
Примечание: Если в вашем классе Health
нет метода abstract
, вы можете удалить ключевое слово abstract
также из самого определения класса и сделать его только public class Health : MonoBehaviour
.Однако, если вы хотите строго предотвратить создание экземпляра самого базового класса Health
, вы можете сохранить его, чтобы гарантировать, что могут существовать только компоненты наследуемых типов.
Теперь вы можете создавать различные реализации Health
, либо не изменяя его вообще
public class NormalHealth : Health
{
// since it is abstract we have to implement Die
public override void Die()
{
// whatever happens here
}
// But if we want to use the default TakeDamage we just do nothing
}
, либо переписывая поведение по умолчанию
public class WeakHealth : Health
{
// Since it is abstract we have to implement Die
public override void Die()
{
// whatever happens here
}
// Now we replace the TakeDamage
public override void TakeDamage()
{
// by not calling base.TakeDamage we don't execute the base implementation at all
Debug.Log("Huge Ouch!");
health -= 10;
}
}
, либо расширяявместо замены
public class HealthWithSound : Health
{
public AudioSource someAudioSource;
public AudioClip someClip;
// Since it is abstract we have to implement Die
public override void Die()
{
// whatever happens here
}
// This time we only extend the base's TakeDamage with e.g. sound
public override void TakeDamage()
{
base.TakeDamage();
someAudioSource.PlayOneShot(someClip);
}
}