Dog*_*n25 2 c# unity-game-engine
我对 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是playerstats(defaultstats)脚本仅供参考,我试图从中获取物理伤害
[SerializeField] 浮动强度 = 5f; [SerializeField] 浮动物理伤害 = 5f;
public float GetPhysicalDamage()
{
return physicalDamage += strength;
}
Run Code Online (Sandbox Code Playgroud)
抱歉,如果这看起来非常基础,但如果您感到无聊,请看一下!
您正在尝试修改一个函数:
defaultStats.GetPhysicalDamage()-= armor;
Run Code Online (Sandbox Code Playgroud)
但你不能,因为GetPhysicalDamage只返回损坏,它没有设置为允许你修改它的属性(并且也不要这样做!)
public float GetPhysicalDamage()
{
return physicalDamage += strength;
}
Run Code Online (Sandbox Code Playgroud)
相反,看起来您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();
}
}
Run Code Online (Sandbox Code Playgroud)
事实上,经过仔细审查,我认为您可能没有做您认为自己正在做的事情。它看起来physicalDamage应该是你正在造成的基础伤害,但是当你有如下一行时GetPhysicalDamage():
return physicalDamage += strength;
Run Code Online (Sandbox Code Playgroud)
如果physicalDamage是5并且strength是5,那么你第一次打电话时GetPhysicalDamage()你会得到10。但是你所做的是增加物理伤害的强度,并将该值存储为+=操作员的新物理伤害,这样下次你打电话时GetPhysicalDamage()变量physicalDamage现在是 10(来自上一次调用),现在返回 15。然后是 20、25 等。
我认为你想要的只是物理伤害和力量的总和,例如:
return physicalDamage + strength;
Run Code Online (Sandbox Code Playgroud)
但如果是这种情况,那么我认为变量名称physicalDamage具有误导性。我个人更喜欢这样的东西basePhysicalDamage,然后你可以拥有这样的财产:
public int PhysicalDamage => basePhysicalDamage + strength;
Run Code Online (Sandbox Code Playgroud)
我特别建议这样做,因为稍后在您的代码中,您现在遇到问题,您将physicalDamage在以下行修改变量:
physicalDamage = Mathf.Clamp(physicalDamage, 0, int.MaxValue);
Run Code Online (Sandbox Code Playgroud)
这也很令人困惑,因为看起来您正在尝试使用 来GetPhysicalDamage修改它armor,但是当您调用GetPhysicalDamage并且armor您从同一(本地)源获取它们时,因此这将是玩家对自己造成的物理伤害玩家的护甲,或者是生物的护甲对自己造成的物理伤害。
我会将损坏作为参数传递,以便您可以将损坏从一件事发送到另一件事,例如:
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();
}
}
Run Code Online (Sandbox Code Playgroud)