【问题标题】:How can i add random texts to Unity Textmesh?如何向 Unity Textmesh 添加随机文本?
【发布时间】:2021-02-20 21:18:44
【问题描述】:

我是一个团结的初学者,对编程知之甚少。

对于一个统一的游戏场景,我需要提取应该显示在 textmesh 画布中的随机文本。

有人可以帮助我了解初学者友好的操作方法吗?

我发现这篇文章描述了一些代码如何做到这一点......

已编辑(这是正确的链接): https://answers.unity.com/questions/756090/how-can-i-change-textmesh-to-a-random-text-snippet.html

但是这段代码怎么实现呢。

我会创建一个新的 cs-script 文件。除了提到的代码之外,我还应该包括什么?以及如何将其连接到游戏场景画布中的 textmesh 对象?

希望你能帮助我,很抱歉问了这么愚蠢/基本的事情!

一切顺利, 标记

【问题讨论】:

标签: c# unity3d


【解决方案1】:

我发现最好的方法是使用字符串数组:

string[] words = { "word A", "word B" }; etc...

然后你可以调用这行代码,里面会有你的随机词

string randomWord = words[Random.Range(0, words.Length)];

好的,这个怎么用?

这是一种方法:

using UnityEngine;
using TMPro;


public class something : MonoBehaviour
{
    public string[] words = { "Word A", "Word B" };
    public TMP_Text text;

    private void Start()
    {
        // log whatever comes out of the RandomWord string.
        string wordToDisplay = RandomWord();

        text.text = wordToDislpay;
    }

    // when you see a string function,
    // it will return a string that
    // you can use anywhere!
    private string RandomWord()
    {
        // grab a random string from the words array
        string randomWord = words[Random.Range(0, randomWord.Length)];

        // return it (this will be the string that the script will use)
        return randomWord;
    }
}

如果您使用的是普通 UI 文本而不是 TEXT MESH PRO,则不要使用TMPro;,而是使用using UnityEngine.UI;,而TMP_Text 将只是Text。可以在inspector中更改字符串数组,这是最好的一点!

你应该可以用这个做任何你想做的事情。

祝大家团结一致!

【讨论】:

  • 如果你不知道,text mesh pro 只是 unity 原始 ui 文本的一个更好的版本,只是因为它的文本更清晰,而不是 unity 的股票具有的模糊文本。
  • 嘿,谢谢你的回答!是的,很明显 textmesh 只是高级常规文本。我将尝试该代码,并会回来提供反馈。非常感谢您的帮助!
  • 试过了,这是我得到的错误代码:Assets/Journey/Scripts/Others/RandomText1.cs(24,51): error CS0165: Use of unassigned local variable 'randomWord'
  • 这是使用的脚本
【解决方案2】:

我能够使用此代码解决它。

非常感谢你!!!!

using UnityEngine;
using TMPro;


public class RandomText1 : MonoBehaviour
{
    public string[] words = { "XA", "XB", "XC" };
    public TMP_Text text;

    private void Start()
    {
        // log whatever comes out of the RandomWord string.
        string wordToDisplay = RandomWord();

        text.text = wordToDisplay;
    }

    // when you see a string function,
    // it will return a string that
    // you can use anywhere!
    private string RandomWord()
    {
        // grab a random string from the words array
        string randomWord = words[Random.Range(0, words.Length)];

        // return it (this will be the string that the script will use)
        return randomWord;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2012-10-12
    • 2014-01-16
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多