C# - 公共Getter和受保护的固定器接口
您好,我正在从事统一游戏,我想创建生物实体。
要执行此操作,我想为所有具有健康的实体创建一个界面
是我的生活界面:
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...}
}
但是,在我的情况下,如果我仅在儿童类实施,我无法在接口中为“ RegenHP”方法提供任何代码。
如何执行此操作?
Hello i'm working on a Unity game and i would like to create living entities.
To perform this, i want to create an interface for all entities having health
Here is my interface for 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;
}
}
The point is:
- I need the hp to be public in get
- I want to give code in my interface for the hp regeneration per second (to not re implement the same code in each living entity)
- I want the hp to be set only from the living entities themself
I saw tricks like this:
in interface:
public float Hp{get;}
and in implementation:
public float Hp{
get{code...}
protected set{code...}
}
but in my case, if i define the setter only in the child class implementation, i'm not able to give any code for my 'regenHp' method in interface.
How to perform this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以利用Unity内置的组件设计中的unity内置的组件设计,而不是使用抽象的基类,这是解决此类问题的标准方式。它通常由许多组件组成的游戏对象。
您可以定义一个共享组件:
然后在主要组件中依赖它:
如果重要的是您仍然具有仅读取界面,则也可以执行此操作:
Rather than using an abstract base class as was suggested in a comment, you can leverage Unity's built in component design which is the standard way of solving such a problem. Its common for game objects to be composed of many components.
You can define a shared component like:
And then depend on it in your main components:
And if its important that you still have a read-only interface, you can do that too: