【问题标题】:Why can't I set a Unity.UI.Text object to a string?为什么我不能将 Unity.UI.Text 对象设置为字符串?
【发布时间】:2021-11-13 03:44:47
【问题描述】:

所以我正在尝试为我的游戏创建一个计分器,并且我希望它每次都增加并且敌人被杀死。但是,当我尝试将分数设置为之前的值 + 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”。 为什么会出现此错误?

【问题讨论】:

  • (int.Parse(score.text) ...

标签: string unity3d text type-conversion integer


【解决方案1】:

问题是您正在解析作为 UnityEngine UI 文本组件的分数对象,而不是将其更改为:

score.text = (int.Parse(score.text) + 1).ToString();

我还建议使用单独的分数整数变量来存储分数。 因此,您可以将 scoreText 作为 UnityEngine UI 文本并将 score 作为 Integer,然后您可以执行以下操作:

score++;

scoreText.text = $"{score}";

旁注:

请不要使用这些类型的作业:

score = GameObject.Find("Canvas/Text").GetComponent<Text>();

对于这种特定情况,您可以通过添加以下内容从 UnityEditor 分配文本组件:

[SerializeField] private Text score;

并摆脱你在 Start 函数中所做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    相关资源
    最近更新 更多