在遊戲開發過程中用UGUI做聊天界面時,其中聊天氣泡會随着聊天内容地長度做自适應。
需要在氣泡圖檔上,添加兩個元件,Horizontal Layout Group和Content Size Fitter,下面詳細介紹一下這兩個元件。
Horizontal Layout Group:
Padding : 包括布局元素距離四個方位的距離,Left : 左邊緣 , right : 右邊緣 , top : 頂邊緣 , bottom : 底邊緣
Spacing : 布局元素之間的距離
Child Alignment : 對齊方式
Child Controls Size : 兩個可選項,是否控制元素的的寬和高。
Child Force Expand : 兩個可選項
width : 是否強行擴大布局元素寬度以填補額外可用的空間
Height : 是否強行擴大布局元素高度以填補額外可用的空間
Content Size Fitter:
content Size Fitter元件是用來設定UI的長度,Horizontal Fit和Vertical Fit分别是控制UI的寬和高,有三個值可選:
Unconstrained : 元件不根據布局元素調整,可手動修改長寬的值
MinSize : 根據布局元素的最小來調整,不能手動修改長度值
PreferredSize : 根據布局元素的内容來調整,不能手動修改長寬的值。
将輸入消息顯示出來(代碼):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Chat : MonoBehaviour {
public Text chat; //顯示消息
public InputField input; //輸入消息
List<string> strs = new List<string>();
int length; //得到輸入地長度
int singleLength = 15; //單行長度
void Start () {
}
void Update () {
if (Input.GetKeyDown(KeyCode.Return) && input.text != null)
{
length = input.text.Length;
int index = length / singleLength;
for (int i = 0; i <= index; i++)
{
//将單行文本放入字元連結清單中
if (input.text.Substring(i * singleLength).Length > singleLength)
{
strs.Add(input.text.Substring(i * singleLength, singleLength) + "\n");
}
else
{
strs.Add(input.text.Substring(i * singleLength));
}
}
foreach (var item in strs)
{
chat.text += item;
}
strs.Clear();
input.text = "";
}
}
}
效果圖:
注:
氣泡圖需要使用九宮格進行切割:
然後将圖檔的Image元件,Image Type設定為Slied.