Unityではオブジェクト指向のプログラミングの概念は引き続き使用できますコンポーネントからエンティティを構築します。
using UnityEngine;
public abstract class Character : MonoBehaviour
{
public int HitPoints { get; set; }
public virtual void ChangeHP(int amount)
{
HitPoints += amount;
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("DeathTrigger"))
{
Die();
}
}
protected virtual void Die()
{
Debug.Log("I'm dead.");
}
}
public class LordOfTerror : Character
{
protected override void Die()
{
base.Die();
Debug.Log("But I also come back from the dead very soon.");
HitPoints = 100;
}
}
しかし、プログラミングのこの種は、わずかな継承ツリーのために働き、わずか数制限または回避策を使用すると、ユニティにに慣れるしなければならないことは事実です。一般的に、可能な限りコンポーネントを使用することは理にかなっています。
using System;
using UnityEngine;
public abstract class StatAttribute
{
public int current;
public int min;
public int max;
public void Change(int amount)
{
current += amount;
}
}
public sealed class Health : StatAttribute
{
public event Action tookDamage;
public bool isAlive
{
get { return current > min; }
}
public void Damage(int amount)
{
base.Change(-amount);
// also fire an event to make other components play an animation etc.
if(tookDamage != null)
tookDamage();
}
}
public sealed class Speed : StatAttribute
{
public int boost;
public int GetFinalSpeed()
{
return base.current * boost;
}
}
通常、ゲームオブジェクトにアタッチされた個々のコンポーネントから始めます。すべての組み合わせはあなたの文字を構成します。あなたの通知がそのコードが重複しているいくつかの点でなど健康、CharacterMovement、PlayerInput、アニメーション、のようなものを持っており、これはコンポーネント間の特定の基底クラスを共有するのは意味があります場所です。
サブクラスが異なるデフォルト値または異なる定数値を設定することを意味しますか? –
これはあまりにも一般的な質問です。これまでに試したことが分かりますか? – bodangly
デフォルト値を設定する(すなわち、文字レベルとして最大HPを変更する) – Edogmonkey