Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 应增加1分时,得分增加2分_C#_Unity3d - Fatal编程技术网

C# 应增加1分时,得分增加2分

C# 应增加1分时,得分增加2分,c#,unity3d,C#,Unity3d,我有一颗子弹,当它击中目标时,它应该增加1分。但是分数增加了2分。子弹是一个装有对撞机和刚体的胶囊,目标是一个装有对撞机和刚体的圆柱体 子弹上的密码 public class Bullet : MonoBehaviour { float lifespan = 2; void Start() { // destroy the bullet Destroy(gameObject, lifespan); } void OnTriggerEnter(Collider

我有一颗子弹,当它击中目标时,它应该增加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;
 }
}
公共课堂分数:单一行为{
public static int score;//玩家的分数。
Text Text;//对文本组件的引用。
void Start()
{
//设置引用。
text=GetComponent();
//重设分数。
得分=0;
} 
无效更新()
{
//将显示的文本设置为分数值。
text.text=“分数:”+分数;
}
}

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

有两个可能的原因导致你的分数会多次更新

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

修复:

A。检查
gameObject.AddComponent()不在项目中任何脚本中的任何位置。
AddComponent
将向游戏对象添加新的子弹

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

选择
项目符号
脚本,转到资源-->在场景中查找引用。它将向您显示每个附加了此脚本的游戏对象。将其从除子弹游戏对象之外的所有对象中移除

2。游戏对象上有多个碰撞器。也许是小时候的对撞机。你必须找到一个方法来解决这个问题。如果是这种情况,可以通过将子碰撞器放在单独的标记中并进行检查来忽略它们


你已经在检查标签了,没问题。只需将子碰撞器的标记更改为非“Score”的其他标记,以便
other.gameObject.CompareTag(“Score”)
不会为
true

使用调试器,并检查方法
OnTriggerEnter
是否启动了两次。请查看此项:另外,请检查是否在任何对象上有2个碰撞器。谢谢,在空的预制对象上有脚本。这就解决了问题