using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //文字按钮控制类 设置文字时动态改变按钮高度 确保显示所有文字 public class TextButtonCtrl : MonoBehaviour { [SerializeField] Text text_msg =null; [SerializeField] RectTransform button_trans=null; TextGenerator generator = new TextGenerator(); TextGenerationSettings settings; [SerializeField] float pading=5;//按钮与文字之间预留的空白区域 默认文字居中 上下一致 public void SetStr(string str) { if(settings.font==null) settings = text_msg.GetGenerationSettings(text_msg.rectTransform.rect.size);//获取Text 的实际尺寸 if (settings.horizontalOverflow == HorizontalWrapMode.Overflow)//不能设置为横向扩展 否则无法正确计算高度 settings.horizontalOverflow = HorizontalWrapMode.Wrap; float value = generator.GetPreferredHeight(str, settings); Vector2 size = button_trans.sizeDelta; size.y = value+ pading*2; //Debug.Log(size.y); button_trans.sizeDelta = size; text_msg.text = str; } }