继承时隐藏子类中的字段

问题描述 投票:0回答:1

在继承时,不使用自定义检查器,真的无法在子类的检查器中隐藏这两个字段吗?

如果是,那么更改

currentState
类中
EnemyBattleLogic
的值的最佳方法是什么?

谢谢!

enter image description here

public class EnemyMoveLogic : MonoBehaviour
{
    [SerializeField, Range(1f, 10f)] internal float movingSpeed;
    [SerializeField] internal float detectionDistance;

    internal GameObject player;
    internal NavMeshAgent agent;

    internal enum CurrentState
    {
        Sleep,
        Patrol,
        Chase
    }

    internal CurrentState currentState = CurrentState.Sleep;
public class EnemyBattleLogic : EnemyMoveLogic
{
    [SerializeField, Range(1f, 5000f)] internal float health;
    [SerializeField, Range(1f, 5000f)] internal float damage;
    [SerializeField, Range(0.1f, 3f)] internal float attackSpeed;
    [SerializeField] internal float attackDistance;
c# unity-game-engine inheritance
1个回答
0
投票
  1. 不,如果您继承了这些字段,则无法隐藏它们。尝试使用拆分组件来拥有不同的逻辑和字段。
  2. 要更改当前状态,您可以通过检查器更改它,如果您输入
    [SerealizedField]
    ,或者如果要在代码中更改它,您可以创建公共函数,如
    SetStateSleep
    SetStatePatrol
    等。当您将来想在这些函数或其他逻辑中添加一些事件调用。

这些是您问题的直接答案,但似乎有一些提示可以帮助您永远不会有这些问题。

  1. 如果您不需要某些变量或逻辑,则不应继承它们。如果您只需要字段或/和逻辑的某些部分,您可能需要拆分基类,因为存在不同的行为。 另外,在您的屏幕截图中,我同时看到
    EnemyMoveLogic
    EnemyBattleLogic
    。您只想更改
    EnemyMoveLogic
    中的值。那么看来你不应该继承
    EnemyMoveLogic
    而只是另一个组件。所以你只会有这些:
public class EnemyMoveLogic : MonoBehaviour
{
    [SerializeField, Range(1f, 10f)] internal float movingSpeed;
    [SerializeField] internal float detectionDistance;

    internal GameObject player;
    internal NavMeshAgent agent;

    internal enum CurrentState
    {
        Sleep,
        Patrol,
        Chase
    }

    internal CurrentState currentState = CurrentState.Sleep;

    public void SetStateSleep()
    {
        // Some other logic
        currentState = CurrentState.Sleep;
        //Some other logic
    }

    // Other State change funcs...
}

// You can also split this class as there might be units that don't attack
// absurd but happened in my game
public class EnemyUnitLogic : MonoBehaviour
{
    [SerializeField, Range(1f, 5000f)] internal float health;
    [SerializeField, Range(1f, 5000f)] internal float damage;
    [SerializeField, Range(0.1f, 3f)] internal float attackSpeed;
    [SerializeField] internal float attackDistance;
}

还有很多其他想法可以使代码变得更好,但将其留在this问题下是不正确的。这可能是一场巨大的讨论。别着急,体验准时到来。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.