我怎样才能停止重复添加浮点数并制作非常大的数字但仍然希望代码更新浮点数

How can I stop floats being added repeatedly and making really big numbers but still wanting the code to update the floats

基本上,我的代码存在问题,该代码根据它击中的 body 部分(或碰撞器)造成伤害。它工作正常,除了播放器 object 中的部分( parent object 包含所有肢体和 body 部分)我希望它添加所有单独的健康body 部分和它一起成为一个名为 currentHealth 的浮点数。添加部分也完全可以正常工作,只是它在更新中不断添加数字。我已经尝试了一些解决方案,但意识到我需要在更新中添加浮点数,因为我需要在浮点数受到损坏时进行更改。另一件需要注意的事情是,承受伤害功能是在单独的肢体健康脚本上,这意味着我不能为我的玩家将浮动添加的东西放在承受伤害功能中。下面我粘贴了我正在谈论的代码。

currentHealth = head.currentHeadHealth += body.currentBodyHealth += lArm.currentLeftArmHealth += rArm.currentRightArmHealth += lHand.currentLeftHandHealth += rHand.currentRightHandHealth += lLeg.currentLeftLegHealth += rLeg.currentRightLegHealth += lFoot.currentLeftFootHealth += rFoot.currentRightFootHealth; 

(上面的代码在update函数中) 所有名为 current?health 的浮点数都来自脚本顶部引用的每个脚本。

    public float playerHealth;
    public float currentHealth;
    public healthBar healthBar;
    public TextMeshProUGUI hpAmount;
    public headHealth head;
    public bodyHealth body;
    public Leftarmhealth lArm;
    public Rightarmhealth rArm;
    public Lefthandhealth lHand;
    public Righthandhealth rHand;
    public Leftleghealth lLeg;
    public Rightleghealth rLeg;
    public Leftfoothealth lFoot;
    public Rightfoothealth rFoot;

编辑:忘了说(对不起是我的错)但我有不同脚本的原因是因为每个肢体,即头部或左腿都有特殊的脚本,比如头部只有一个铰链关节 2d,我想在currentHeadHealth 达到 0,而右臂需要禁用连接的手的铰链关节、手臂控制器脚本和手控制器脚本。这就是所有单独脚本的原因,因为每个脚本都有不同的组件需要禁用

我猜你只想使用 + 而不是 +=


x += y

基本上就是

x = x + y 

所以您告诉每个 float 字段在计算总和的同时增加它们后面的值。

作为发生情况的一个较短的例子

float a = 1;
float b = 2;
float c = 3;

var x = a += b += c;

将导致

a : 6
b : 5
c : 3

x : 6

为什么?因为内部发生的是下面的

b = b + c; // 2 + 3 -> 5
a = a + b; // 1 + 5 -> 6
x = a;

你可能只是想做

currentHealth = head.currentHeadHealth 
                + body.currentBodyHealth 
                + lArm.currentLeftArmHealth 
                + rArm.currentRightArmHealth 
                + lHand.currentLeftHandHealth 
                + rHand.currentRightHandHealth 
                + lLeg.currentLeftLegHealth 
                + rLeg.currentRightLegHealth 
                + lFoot.currentLeftFootHealth 
                + rFoot.currentRightFootHealth;   

嗯,首先我觉得它有点乱。我没有看到你的项目,但我可以给你一个建议:不要为同一目标创建单独的脚本。如果您的所有部分都有一个独特的脚本,那可能就没有必要了。 (如果 body 部分字段不是 object,请忽略此内容。)

所以我的建议是,不要出于同样的原因(存储健康和受到伤害)创建单独的 类,而是只创建一个,然后将其存储在 parent object.

像这样:

public class BodyPartHealth
{
   public float health = 10f;

   public void ReceiveDamage(float damage)
   {
       health -= damage;
       health = Mathf.Clamp(health, 0, 10f);
   }
}

那么 parent 脚本可能如下所示:

public class ParentScript
{
   public List<BodyPartHealth> bodyParts = new List<BodyPartHealth>();
   public float playerHealth;
   public float currentHealth;

   public void Update()
   {
       currentHealth = 0;
       foreach(BodyPartHealth part in bodyParts)
       {
           currentHealth += part.health;
       }
   }
}

这将确保您的代码易于阅读并且可以快速管理。

BodyPartHealth 脚本附加到您的 body 部件,然后将部件添加到检查器中的 parent 列表。