温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Why do I sometimes get double increases in my score when I catch a star?
c# unity3d

c# - 为什么当我接一颗星时我的分数有时会增加一倍?

发布于 2020-03-27 12:09:41

我目前正在开发视频游戏,现在遇到的一个问题是,当我测试游戏时,当我获得一颗星时,我的得分经常会增加两倍或三倍。有谁知道为什么会这样?在下面,您将找到处理分数增加的脚本。提前致谢

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

查看更多

查看更多

提问者
Maurice Bekambo
被浏览
83
Ruzihm 2019-07-04 01:26

一种选择是在与球发生碰撞后立即禁用对恒星的碰撞。要在合并的恒星上使用此功能,您需要在再次启用恒星时重新启用碰撞:

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;
        }
    }
}