我目前正在从事视频游戏,现在遇到一个问题是,当我测试游戏时,当我获得一颗星时,我的得分经常会增加两倍或三倍。有谁知道为什么会这样?在下面,您将找到处理分数增加的脚本。预先感谢
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StarCollision : MonoBehaviour
{
int Score;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("White Ball")) // Change this from an update method that runs every frame to a method that only runs when things change (Score script score display method)
{
Score = ScoreScript.scoreValue;
ScoreScript.scoreValue += 1;
StartCoroutine(ChangeColor());
Score = ScoreScript.scoreValue;
if (Score == ScoreScript.scoreValue)
{
Debug.Log("My instance: " + GetInstanceID());
Debug.Log("Other instance: " + other.gameObject.GetInstanceID());
}
}
}
private IEnumerator ChangeColor()
{
ScoreScript.score.color = Color.yellow;
yield return new WaitForSeconds(0.1f);
ScoreScript.score.color = Color.white;
gameObject.SetActive(false);
}
}
每一颗被捕获的星星分数只会增加1
答案 0 :(得分:1)
一种选择是在与球发生碰撞后立即禁用对恒星的碰撞。要在合并的恒星上使用此功能,您需要在再次启用恒星时重新启用碰撞:
Collider2D myCollider;
private void Awake()
{
myCollider = GetComponent<Collider2D>();
}
private void OnEnable()
{
myCollider.enabled = true;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("White Ball"))
{
// Disable this collider immediately to prevent redundant scoring, sound cues, etc.
myCollider.enabled = false;
ScoreScript.scoreValue += 1;
StartCoroutine(ChangeColor());
}
}
如果您确定协程发生时需要与恒星发生碰撞,则可以在StarCollision
中添加一个字段,以确保分数只会增加一次。同样,对于汇集星,您需要确保在OnEnable
中将其重置:
private bool alreadyScored = false;
private void OnEnable()
{
alreadyScored = false;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("White Ball"))
{
if (!alreadyScored)
{
ScoreScript.scoreValue += 1;
StartCoroutine(ChangeColor());
alreadyScored = true;
}
}
}