【问题标题】:What is the best way to convert a UI text to string in Unity (C#)?在 Unity (C#) 中将 UI 文本转换为字符串的最佳方法是什么?
【发布时间】:2019-02-02 12:54:11
【问题描述】:

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

错误:资产/脚本/ChangeQuestion1.cs(15,26):错误 CS0029:不能 隐式转换类型UnityEngine.UI.Text' tostring

将 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 () {

    }
}

更新:

我已经解决了这个问题,比这更复杂。我试图在画布中打印的变量来自连接数据库的脚本,我也忘了调用一些函数。

【问题讨论】:

  • Question1.text = Question1; 没有逻辑意义,您试图将对象的 text 属性分配为对象本身
  • GetComponent&lt;GameObject&gt;() 也没有意义..
  • 我更新了帖子,看看
  • 尝试打印 Question1。 Debug.Log(Question1Display.GetComponent&lt;DatabaseInterface&gt;().Question1); 。它打印任何东西吗?另外,yourText 分配是否正确?
  • 我已经解决了这个问题,比这更复杂。我试图在画布中打印的变量来自连接数据库的脚本,我也忘了调用一些函数。

标签: c# visual-studio unity3d


【解决方案1】:

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 () {

    }
}

【讨论】:

  • GetComponent&lt;GameObject&gt;() 仍然没有意义
  • 我正在尝试根据另一个函数中的变量值转换 ui 文本。对不起,不是很清楚。
猜你喜欢
  • 2010-09-17
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 2011-04-25
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多