你好,我正在做一个统一的游戏,我想创造生命实体.

要执行此操作,我想为所有具有运行状况的实体创建一个接口

以下是我的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再生的代码(不要在每个活体中重新实现相同的代码)
  • 我希望hp只能从活体自身设置

我见过这样的把戏:

在界面中:

public float Hp{get;}

在实施过程中:

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

但在我的例子中,如果我只在子类实现中定义setter,我无法在接口中为我的"regenHp"方法提供任何代码.

怎么做?

推荐答案

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

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

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;

Csharp相关问答推荐

后台线程上的延迟WriteableBitmap写入导致闪烁

VB.Net的SON模式导致集合代码不工作

C# Json重新初始化动态类型

使用yaml将Azure函数代码部署到FunctionApp插槽时出现问题(zip未找到)

如何阻止注释被包含在C#release build. exe中

C#DateTime.ToString在ubuntu和centos中返回不同的结果

从ASP.NET Core中的枚举字段填充 Select 选项时,将默认的第一个选项添加为 Select 元素

System.Net.Http.HttpClient.SendAsync(request)在docker容器内的POST方法30秒后停止

在此系统上已禁用获取正在运行的脚本.&在ASP.NET Core Web API中

ASP.NET核心MVC SqlException:违反主键约束';PK_USER';.无法在对象';数据库中插入重复的密钥.用户';

.NET SDK包中的官方C#编译器在哪里?

System.Text.Json .NET 8多形态语法化

具有可空类型的C#NOTNULL约束具有意外行为

当试图限制EF Select 的列时,如何避免重复代码?

基于C#和ANGING的SignalR实时聊天流媒体应用

WinUI 3中DoubleCollection崩溃应用程序类型的依赖属性

使用switch 类型模式时出现奇怪的编译器行为

Celler ArgumentExpression是否期望在所有情况下都捕获允许空值的运算符?

未在Windows上运行的Maui项目

在.NET Maui中,Flyoutindow/Hamburger菜单可以在shell 之外实现吗?