我正在 Unity 中從事一個愛好專案。我的角色有MonoBehaviour腳本,這些腳本對角色的每種行為使用組件物件。當我創建新角色時,我會從基類中繼承一個新類,用于表現不同的組件。
當某些觸發器發生時,我通過呼叫Reset()基類公開的方法將字符回傳到它們的初始狀態,該方法將欄位設定回它們的初始值。我想知道如何通過繼承鏈發送該呼叫。現在,基類有一個受保護的虛擬ChildReset(),它被呼叫Reset()并且默認情況下什么都不做。如果子類有要重置的欄位,它們會覆寫此方法。感覺這是一種非常尷尬的做法。
我喜歡實作類似于Unity 使用的訊息傳遞系統的想法。如果一個單一行為不使用該Update()訊息,那么該類就沒有定義更新。它消除了不必要的呼叫。我不知道我會怎么做這樣的事情。
對此投入的任何想法都非常感謝!我已經在下面寫出了我的專案的結構方式,以防這些細節對答案有用。
public class Character : MonoBehaviour
{
private Motion motionController;
private Interaction characterInteractionController;
//etc
private void Update()
{
motionController.DoStuff();
characterInteractionController.DoStuff();
}
private void Reset()
{
motionController.Reset();
characterInteractionController.Reset();
}
private void OnEnable() => ResetTrigger.OnReset = Reset;
private void OnDisable() => ResetTrigger.OnReset -= Reset;
}
public class Motion : Component {}
public class Interaction : Component {}
public abstract class Component
{
public void Reset()
{
/* set fields to default values */
ChildReset();
}
protected virtual void ChildReset() { }
public abstract void DoStuff();
}
uj5u.com熱心網友回復:
There is no need to send a call down through the inheritance chain. You do not have two different objects. An object of the child class contains everything declared in the base class. Why not directly make Reset() virtual?
public abstract class Character : MonoBehaviour
{
public virtual void Reset()
{
...
}
}
public class ChildCharacter : Character
{
// If ChildCharacter has stuff to reset, override this method, otherwise don't!
public override void Reset()
{
base.Reset(); // Call this to reset stuff from the base class.
//TODO: reset child stuff.
}
}
If Reset is overridden in the child class, then calling Reset will call ChildCharacter.Reset() even if called on a variable statically typed as Character.
Character c = new ChildCharacter();
c.Reset(); // calls ChildCharacter.Reset() when overridden
If Reset is not overridden in the child class, then calling Reset will call Character.Reset() even if called on a ChildCharacter.
ChildCharacter child = new ChildCharacter();
c.Reset(); // calls Character.Reset() when not overridden.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/428481.html
上一篇:具有相同值的分組聯合表(文章)
下一篇:忽略所有物件的碰撞
