我正在尝试创造一个统一的分数,如果你收集硬币(在我的例子中是炮弹),分数每次上升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
游戏对象中增加ScoreTextScript
game Object中的coinAmount
字段,并保持ScoreTextScript
game 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