在Unity(C#)中将UI文本转换为字符串的最佳方法是什么?

时间:2019-02-02 12:54:12

标签: c# visual-studio unity3d

我正在尝试编写一个代码,该代码通过另一个函数中的字符串变量来更改UI的文本,但我知道了

  

错误:Assets / Scripts / ChangeQuestion1.cs(15,26):错误CS0029:无法   隐式转换类型UnityEngine.UI.Text' to字符串

将UI文本转换为字符串的最佳方法是什么? 如果这个问题听起来不好,我很抱歉。 这是代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChangeQuestion1 : MonoBehaviour {

    public GameObject databaseinterfaceinstance;

    public Text Question1;
    // Use this for initialization
    void Start () {
        databaseinterfaceinstance = GameObject.FindWithTag("DatabaseInterface").GetComponent<GameObject>();
        Question1 = gameObject.GetComponent<Text>();
        Question1.text = Question1;
    }

    // Update is called once per frame
    void Update () {

    }
}

更新:

我已经解决了这个问题,它比那还要复杂。我试图在画布上打印的变量是从脚本连接数据库的,而我也忘记了调用某些函数。

1 个答案:

答案 0 :(得分:3)

Question1.text的类型为string,并且您尝试将其值设置为Question1,其类型为UnityEngine.UI.Text。您只能将其值设置为string,因此应为:

Question1.text = yourText; 

Question1.text = "Your text goes here";

这就是代码中的样子:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChangeQuestion1 : MonoBehaviour {

    public GameObject databaseinterfaceinstance;

    public Text Question1;
    public string yourText = "Your text goes here";
    // Use this for initialization
    void Start () {
        databaseinterfaceinstance = GameObject.FindWithTag("DatabaseInterface").GetComponent<GameObject>();
        Question1 = gameObject.GetComponent<Text>();
        Question1.text = yourText;
    }

    // Update is called once per frame
    void Update () {

    }
}