gpt4 book ai didi

c# - 应该增加 1 的分数增加 2

转载 作者:行者123 更新时间:2023-11-30 20:31:18 24 4
gpt4 key购买 nike

我有一颗子弹,当它击中目标时,它应该将分数增加 1。但分数增加了 2。子弹是带有碰撞器和刚体的胶囊,目标是带有碰撞器和刚体的圆柱体

子弹上的代码

public class Bullet : MonoBehaviour {

float lifespan = 2;

void Start()
{
// destroy the bullet
Destroy(gameObject, lifespan);
}

void OnTriggerEnter(Collider other) //collider event
{
if (other.gameObject.CompareTag("Score"))
{
Score.score = Score.score + 1;
}
}
}

分数代码

public class Score : MonoBehaviour {

public static int score; // The player's score.

Text text; // Reference to the Text component.

void Start()
{
// Set up the reference.
text = GetComponent<Text>();

// Reset the score.
score = 0;
}

void Update()
{
// Set the displayed text to the score value.
text.text = "Score: " + score;
}
}

最佳答案

我之前已经解决了这个确切的问题,但我搜索它以将其标记为重复但找不到它。它可能已被 OP 删除。

您的分数可能会更新多次的原因可能有 2 个。

1。您的脚本 ( Bullet ) 多次附加到您的游戏对象。这很可能是问题所在。它很可能附加到随机的空 GameObject。

修复:

A。检查 gameObject.AddComponent<Bullet>();不在项目的任何脚本中。 AddComponent将为您的游戏对象添加新的 Bullet。

B。通过编辑器在游戏对象上搜索重复的脚本。

选择您的 Bullet脚本,转到 Assets --> 在场景中查找引用。它将向您显示每个附加了此脚本的游戏对象。除了你的 bullet GameObject 之外,将其从所有对象中删除。

enter image description here

2。您在 GameObject 上有多个对撞机。也许小时候是对撞机。你必须找到一种方法来处理它。如果是这种情况,您可以通过将它们放在单独的标签中并检查它来忽略子碰撞器。

您已经在检查标签了,这没问题。只需将子碰撞器的标签更改为不是"Score" 的其他内容,这样 other.gameObject.CompareTag("Score")不会是true .

关于c# - 应该增加 1 的分数增加 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43455365/

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