为什么不能将 Unity.UI.Text 对象设置为字符串?
Why can't I set a Unity.UI.Text object to a string?
所以我正在尝试为我的游戏创建一个计分器,我希望它在每次敌人被杀死时增加。但是,当我尝试将分数设置为其先前的值 + 1 时,我收到一条错误消息:
error CS1503: Argument 1: cannot convert from 'UnityEngine.UI.Text' to 'string'
这是我的代码:
using System.Collections;
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) {
if (shot) {
Destroy(gameObject);
Destroy(other.gameObject);
score.text = (int.Parse(score) + 1).ToString();
}
}
}
文本在开头设置为“0”。
为什么会出现此错误?
问题是您正在解析作为 UnityEngine UI 文本组件的分数对象,而是将其更改为:
score.text = (int.Parse(score.text) + 1).ToString();
我还建议使用一个单独的分数整数变量来存储分数。
所以你会 scoreText as UnityEngine UI Text & score as Integer 然后你可以做这样的事情:
score++;
scoreText.text = $"{score}";
旁注:
请不要使用这些分配:
score = GameObject.Find("Canvas/Text").GetComponent<Text>();
对于这种特定情况,您可以通过添加以下内容从 UnityEditor 分配文本组件:
[SerializeField] private Text score;
并摆脱您在“开始”功能中所做的事情。
所以我正在尝试为我的游戏创建一个计分器,我希望它在每次敌人被杀死时增加。但是,当我尝试将分数设置为其先前的值 + 1 时,我收到一条错误消息:
error CS1503: Argument 1: cannot convert from 'UnityEngine.UI.Text' to 'string'
这是我的代码:
using System.Collections;
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) {
if (shot) {
Destroy(gameObject);
Destroy(other.gameObject);
score.text = (int.Parse(score) + 1).ToString();
}
}
}
文本在开头设置为“0”。 为什么会出现此错误?
问题是您正在解析作为 UnityEngine UI 文本组件的分数对象,而是将其更改为:
score.text = (int.Parse(score.text) + 1).ToString();
我还建议使用一个单独的分数整数变量来存储分数。 所以你会 scoreText as UnityEngine UI Text & score as Integer 然后你可以做这样的事情:
score++;
scoreText.text = $"{score}";
旁注:
请不要使用这些分配:
score = GameObject.Find("Canvas/Text").GetComponent<Text>();
对于这种特定情况,您可以通过添加以下内容从 UnityEditor 分配文本组件:
[SerializeField] private Text score;
并摆脱您在“开始”功能中所做的事情。