gpt4 book ai didi

c# - c# 初学者遇到 CS0131 : The left-hand side of an assignment must be a variable, 属性或索引器问题

转载 作者:行者123 更新时间:2023-12-02 01:31:08 27 4
gpt4 key购买 nike

我对 C# 编码相当陌生,正在尝试自学更多。我一直在尝试制作一个简单的角色扮演游戏,其中包含角色扮演游戏中关卡的统计数据,但一直试图根据我的角色统计数据对敌人施加伤害。

当我认为我已经通过将玩家的统计脚本拆分为敌方单位的第二个统计脚本来解决问题时,不幸的是,我遇到了一个问题,即赋值的左侧需要是一个可变属性或索引器,无论我如何寻找解决方案,我都被难住了。有人可以看一下我的脚本并指出我犯的任何明显错误吗?

请并谢谢您!

   public void TakePhysicalDamage()
{
defaultStats.GetPhysicalDamage()-= armor; //This is the offending line
physicalDamage = Mathf.Clamp(physicalDamage, 0, int.MaxValue);
health -= (int)Math.Round(physicalDamage);

if(health <= 0)
{
health = 0;
Die();
}
}
void Die()
{
{
playerLevel.AddExperience(experience_reward);
}
Destroy(gameObject);
}

}

这里是playerstats(defaultstats)脚本仅供引用,我试图从中获取物理伤害

[SerializeField] float 强度 = 5f;[SerializeField] float 物理伤害 = 5f;

  public float GetPhysicalDamage()
{
return physicalDamage += strength;
}

很抱歉,如果这看起来非常基本,但如果您感到无聊,请看一下!

最佳答案

您正在尝试修改函数:

defaultStats.GetPhysicalDamage()-= armor;

但你不能,因为 GetPhysicalDamage 只返回伤害,它没有设置为允许你修改它的属性(也不要这样做!)

public float GetPhysicalDamage()
{
return physicalDamage += strength;
}

相反,您应该使用一个变量physicalDamage,例如:

public void TakePhysicalDamage()
{
physicalDamage = defaultStats.GetPhysicalDamage() - armor; //This is the offending line
physicalDamage = Mathf.Clamp(physicalDamage, 0, int.MaxValue);
health -= (int)Math.Round(physicalDamage);

if(health <= 0)
{
health = 0;
Die();
}
}

实际上,经过仔细审查,我认为您可能没有做您认为自己正在做的事情。看起来 physicalDamage 应该是您正在造成的基础伤害,但是当您在 GetPhysicalDamage() 中有如下一行时:

return physicalDamage += strength;

如果 physicalDamage 为 5 并且 strength 为 5,那么第一次调用 GetPhysicalDamage() 时,您会得到 10。但是您会得到什么?正在做的是添加物理伤害的强度,并使用+=运算符存储该值作为新的物理伤害,这样下次您调用 GetPhysicalDamage()physicalDamage 变量现在为 10(来自上一次调用),现在返回 15。然后是 20、25,等等。

我认为你想要的只是物理伤害和力量的总和,例如:

return physicalDamage + strength;

但如果是这种情况,那么我认为变量名称 physicalDamage 具有误导性。我个人更喜欢像 basePhysicalDamage 这样的东西,然后你可以拥有这样的属性:

public int PhysicalDamage => basePhysicalDamage + strength;

我特别建议这样做,因为稍后在您的代码中,您现在遇到了问题,您正在修改 physicalDamage 变量,如下所示:

physicalDamage = Mathf.Clamp(physicalDamage, 0, int.MaxValue);

这也很令人困惑,因为看起来您正在尝试 GetPhysicalDamage 并使用 armor 修改它,但是当您调用 GetPhysicalDamagearmor 你从同一个(本地)来源获得它们,所以要么是玩家用玩家的盔甲对自己造成的物理伤害,要么是生物用他们的盔甲。

我会将损坏作为参数传递,以便您可以将损坏从一件事发送到另一件事,例如:

public void TakePhysicalDamage(int damage)
{
damage -= armor;
damage = Mathf.Clamp(damage, 0, int.MaxValue);
health -= (int)Math.Round(damage);
if(health <= 0)
{
health = 0;
Die();
}
}

关于c# - c# 初学者遇到 CS0131 : The left-hand side of an assignment must be a variable, 属性或索引器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73251679/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com