Unity 代码控制Text文本换行

Unity 要通过代码控制Text文本换行,实现方法比较简单,无论是传统的Text,还是TMP文本,都是通过在字符串需要换行的地方加上换行符【\n】。

不过在Text属性栏中要确保设置自动换行模式:

如传统的设置如图:

Unity 代码控制Text文本换行_第1张图片

其实无论哪种,创建的时候换行模式保持默认就行。

代码参考如下:

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

public class TextWrap : MonoBehaviour
{
    public Text text;
    public TextMeshProUGUI TMPtext;
    // Start is called before the first frame update
    void Start()
    {
        text.text = "我是第一行!\n我是第二行!";
        TMPtext.text = "我是第一行!\n我是第二行!";
    }

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

最终效果:

Unity 代码控制Text文本换行

你可能感兴趣的:(unity,游戏引擎,c#)