在Unity游戏中得分只增加1然后停止



我正在尝试创造一个统一的分数,如果你收集硬币(在我的例子中是炮弹),分数每次上升1,然而,分数增加1,然后停止增加,我不知道为什么。

附于硬币(壳)的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ShellController : MonoBehaviour
{
private float coin = 0; // is it because every time player collides with shell, this resets the score back to zero? if so, how do I only set it to zero once, in the beggining? 
public TextMeshProUGUI textCoins;
// Start is called before the first frame update
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
SoundManagerScript.PlaySound("winCoin");
coin ++;
textCoins.text = coin.ToString();
Destroy(gameObject);

}
}
}

这是附在显示分数的标签(文本)上的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreTextScript : MonoBehaviour
{
Text text;
public static int coinAmount;
// Start is called before the first frame update
void Start()
{
text = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
text.text = coinAmount.ToString();
}
}

因为ShellController将被OnTriggerEnter2D事件摧毁,但ShellController首字母coin为每个壳游戏对象的0,所以你可能总是得到1而不是增加数字。

private float coin = 0;
coin ++;
textCoins.text = coin.ToString();

我们可以尝试从每个ShellController游戏对象中增加ScoreTextScriptgame Object中的coinAmount字段,并保持ScoreTextScriptgame Object中的值。

private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
SoundManagerScript.PlaySound("winCoin");        
textCoins.coinAmount++;
Destroy(gameObject);
}
}

这是unity收集金币的一个简单的碰撞方法

void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Player")//If the collision object is the player
{
money++;//money plus one
Destroy(this.gameObject);//Destroy gold coins
}
}

创建金币模型并将上述代码粘贴到其c#代码中以收集金币。如果需要修改现有UI上的货币显示信息

GameObject ifCollect = GameObject.Find("/Canvas/TextTwo");//" "Where is your UI
ifCollect.GetComponent<Text>().text = money.ToString();//Change money

相关内容

最新更新