因此,我正試圖為我的游戲創建一個分數計數器,我希望它在每次殺死敵人時都能遞增。然而,當我試圖將分數設定為之前的值 1時,我得到了一個錯誤提示:
error CS1503: 引數1:不能從'UnityEngine.UI.Text'轉換為'string'
下面是我的代碼:
使用System.Collections.Generic;<
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShieldController : MonoBehaviour
{
Text score;
bool shot = false;
public void LaunchForward(float speed)
{
shot = true;
this.GetComponent<Rigidbody2D>().velocity = transform.up * speed;
}
void Start() {
score = GameObject.Find("Canvas/Text").GetComponent<Text>();
}
void OnCollisionEnter2D(Collision2D other) {
如果(射擊) {
Destroy(gameObject)。
Destroy(other.gameObject);
score.text = (int.Parse(score) 1).ToString();
}
}
}
文本在開始時被設定為 "0"。 為什么我會得到這個錯誤呢?
uj5u.com熱心網友回復:
uj5u.com熱心網友回復:
問題是你正在決議分數物件,它是UnityEngine的UI文本組件,而不是把它改成:
score.text = (int.Parse(score.text) 1).ToString()。
我還建議有一個單獨的分數整數變數來存盤分數。 因此,你將有scoreText作為UnityEngine UI Text & score作為Integer,然后你可以做這樣的事情:
score ;
scoreText.text = $"{score}"。
側面說明:
請不要使用這類作業 :
score = GameObject.Find("Canvas/Text").GetComponent<Text>()。
對于這種特定的情況,你可以通過添加以下內容從UnityEditor分配文本組件:
[SerializeField] private Text score;
并且擺脫你在Start函式中的做法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/324453.html
標籤:
