c# - 在 Unity 检查器上显示从接口(interface)继承的变量

标签 c# unity3d interface

我想在 Unity 中创建一些游戏,我已经开始创建类层次结构以便能够使用多态性。所以我创建了一些既有方法又有变量的接口(interface)。

C# interfaces documentation 中所述, 我用这样的变量创建了我的界面

public interface IUnit : ISelectable {
  int   healthPoint { get; set; }
  bool  isIndestructible { get; set; }
  /******************************/
  void  takeDamage(int dmg);
  void  die();
}

现在,我在一个类中实现我的接口(interface):

[System.Serializable]
public class BasicUnit : MonoBehaviour, IUnit {

  private int       _healthPoint;
  public int        HealthPoint         { get { return (_healthPoint); } set { _healthPoint = value; } }
  private bool      _isIndestructible;
  public bool       isIndestructible    { get { return (_isIndestructible); } set { _isIndestructible = value; } }

  public void   takeDamage (int dmg)
  {
      if (this.isIndestructible == false) {
          this.HealthPoint -= dmg;
          if (this.HealthPoint <= 0) {
              die();
          }
      }
  }

  public void die()
  {
      Destroy(gameObject);
  }
}

我的问题是我的变量 healthPointisIndestructible 没有显示在 Unity 的检查器中,尽管它们是公共(public)变量。我试过使用 [System.Serializable] 但它不起作用。

我的问题很简单,我应该如何在 Unity 的检查器中显示我继承的变量?

注意:我正在尝试编写漂亮且可读的代码,因此如果可能的话,我希望将我的 IUnit 类保留为一个接口(interface),并将我的变量保留在我的 IUnit 中。

最佳答案

隐藏的不是您继承的代码。继承对字段的显示没有任何影响。
相反,真正发生的是您有两个可序列化但标记为私有(private)的字段(_healthPoint 和 _isIndestructible),
和两个公共(public)属性。不幸的是,Unity 无法开箱即用地处理和显示属性。

幸运的是,这里有一个简单的解决方案。我在 Unity Wiki 上找到了这个,并保存它以备不时之需:)

Expose Proerties in Inspector from Unity Wiki

工作原理
基本上,您希望其属性公开的任何 Monobehavior 都应继承自 ExposableMonoBehaviour 以及
1. 私有(private)字段(比如你的 _healthPoint)应该有 [SerializeField, HideInInspector] 属性 2. 公共(public)属性(如 HealthPoint)应具有 [ExposeProperty] 属性

部分例子

public class BasicUnit : ExposableMonoBehaviour, IUnit {

    [SerializeField, HideInInspector]
    private int _healthPoint;
    [ExposeProperty]
    public int HealthPoint { 
        get { return (_healthPoint); } 
        set { _healthPoint = value; } 
    }


}

关于c# - 在 Unity 检查器上显示从接口(interface)继承的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31775893/

相关文章:

java - 集合 <接口(interface)> 名称 = null;

c# - 基于计数的 orderby 相关性的 LINQ 关键字搜索 (LINQ to SQL)

c# - 从多个对象中获取最大值、最小值和平均值的最快、最简单的方法

c# - Unity 私有(private)唤醒更新和启动方法如何工作?

java - 声明一个实现接口(interface)的对象

c# - IList<T> 和 List<T> 与接口(interface)的转换

c# - 从 Active Directory 检索用户名

c# - 如何在wpf中获取文本框的绑定(bind)

c# - 为什么 Unity3d C# 中的 if 语句允许不是 bool 值的对象?

c# - 单击以移动动画不起作用