C# - 公共(public) getter 和 protected setter 接口(interface)

标签 c# unity-game-engine interface protected

您好,我正在开发一款 Unity 游戏,我想创建活体实体。

为了执行此操作,我想为所有具有健康状况的实体创建一个接口(interface)

这是我的 LivingEntities 界面:

public interface ILivingEntity
{
    public float Hp { get; protected set; }
    public float MaxHp { get; protected set; }
    public float HpRegenPerSecond { get; protected set; }

    public event EventHandler Event_died;

    protected virtual void Awake()
    {
        MaxHp = Hp;
    }

    protected virtual void receiveDamage(IAttack attackSource)
    {
        Hp -= attackSource.damage;
        watchForEntityDeadOrNot();
    }

    protected abstract void watchForEntityDeadOrNot();

    protected void regenHp()
    {
        Hp += Time.deltaTime * HpRegenPerSecond;
        if (Hp > MaxHp)
            Hp = MaxHp;
    }
}

重点是:

  • 我需要在 get 中公开 hp
  • 我想在我的界面中提供每秒生命值再生的代码(不要在每个生物实体中重新实现相同的代码)
  • 我希望仅由生物体本身设置生命值

我看到了这样的技巧:

在界面中:

public float Hp{get;}

并在实现中:

public float Hp{
  get{code...}
  protected set{code...}
}

但就我而言,如果我仅在子类实现中定义 setter,我无法为接口(interface)中的“regenHp”方法提供任何代码。

如何执行此操作?

最佳答案

您可以利用 Unity 的内置组件设计,而不是像评论中建议的那样使用抽象基类,这是解决此类问题的标准方法。游戏对象通常由许多组件组成。

您可以定义共享组件,例如:

public class LivingComponent : MonoBehavior
{
    ...
}

然后在你的主要组件中依赖它:

[RequireComponent(typeof(LivingComponent))]
public class SomeLivingThing : MonoBehavior {}

如果您仍然拥有只读界面很重要,您也可以这样做:

public interface ILivingEntity {
   // Getters only here
}

public class LivingComponent : MonoBehavior, ILivingEntity {
   // Implementation
}

// In some other code:
var hp = obj.GetComponent<ILivingEntity>().Hp;

关于C# - 公共(public) getter 和 protected setter 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72199140/

相关文章:

C# 通过 MemoryStream 追加 Pdf 页面

c# - 使用 HtmlAgilityPack 包裹元素?

unity-game-engine - Unity : Having the player face the mouse direction. 为什么这段代码可以工作?

c# - 接口(interface)特定属性

c# - 如何批量远程调用数据库或服务?

c# - 将 MvcHtmlString 与 jQuery 模板一起使用 - 正确的 razor 语法是什么?

ios - 在 iOS 中调用 UIViewController

java - 尝试从 Unity 4.6 中的 Java 插件设置纹理

java - 术语 "Instance variable"和 "variables declared in Interfaces"之间的区别

java - 什么时候应该使用java中的接口(interface)?