在UGUI里Text显示的字符有时候需要个数限制。只需将下面代码绑定到text上就可以了。

namelenth是用来接收文字个数的。在其他脚本里只要设置namelenth这个值就可以。由于Setnamelength()这个方法一直在Update里被调用,所以可以实时的将改变的个数值namelenth传入下面的Setnamelength()这个方法。


本案例中用按键盘P键来限定了传入个数为3。

代码如下:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class namelenthlimit : MonoBehaviour {

public int namelenth=0;//限定字符个数(不分中英文,按个数)



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

if (Input.GetKey(KeyCode.P))
{
this.gameObject.GetComponent<Text>().text = "一行白鹭上青天";
namelenth = 3;
}

Setnamelength(namelenth);
}

public void Setnamelength(int i)//给名字限定i个字符的长度
{
string nameLenthString = this.gameObject.GetComponent<Text>().text;

if (this.gameObject.GetComponent<Text>().text.Length > i)
{
// Debug.Log("长度"+ i);
this.gameObject.GetComponent<Text>().text = nameLenthString.Substring(0, i).ToString() + "…";//截取到指定长度
}
else
return;

}
}



测试效果如下:

UGUI之 Text内容长度限定_Text