Unity UGUI (1) basic components


Record commonly used UI components and usage in UGUI to facilitate reuse.

1. Text: text box

private void Start()
{
    
    
    #region 简介

    //  Text是文本组件
    //  是UGUI中用于显示文本的组件

    #endregion

    #region 参数相关

    _text.font = Resources.Load<Font>("造字工房悦圆");      // 文本字体
    _text.fontStyle = FontStyle.Bold;                       // 文本样式
    _text.fontSize = 40;                                    // 文本大小
    _text.lineSpacing = 1;                                  // 行间距
    _text.supportRichText = true;                           // 是否开启富文本
    _text.alignment = TextAnchor.UpperCenter;               // 文本的水平和垂直对齐方式,对应九宫格的九个位置
    _text.alignByGeometry = true;                           // 以当前所显示的文字中获取最大长宽的那个字作为参考(不勾选以字体中的长宽最大值),进行对齐
    _text.horizontalOverflow = HorizontalWrapMode.Wrap;     // 当选择Overflow时允许水平方向超出文本框范围
    _text.verticalOverflow = VerticalWrapMode.Overflow;     // 当选择Overflow时允许垂直方向超出文本框范围
    _text.resizeTextForBestFit = true;                      // 自动调整字体大小以适应文本框(比较耗费性能,不建议使用)
    _text.color = Color.white;                              // 文本颜色
    _text.material = null;                                  // 文本材质
    _text.maskable = false;                                 // 关闭后父物体的遮罩将不再对其生效
    _text.text = "使用代码修改文本内容~~~~";                  // 文本内容

    #endregion

    #region 富文本示例

    _text.text =                                            // 富文本标签
        "   <b>粗体</b>" +
        "   <i>斜体</i>" +
        "   <b><i>粗体&斜体</i></b>" +
        "   <size=60>字号60</size>" +
        "   <color=#00ff00ff>绿色</color>" +
        "   <color=red>红色</color>";

    #endregion
}

#region 行间距相关
// 一行字的高度等于字体大小
// 行间距为1时,间距的高度是字体大小的一半
private void CheckTextHeightThenSetAnchor(Text text)
{
    
    
    // 只有一行居中,超过一行左对齐
    if(text.preferredHeight > text.fontSize)
    {
    
    
        text.alignment = TextAnchor.MiddleLeft;
    }
    else
    {
    
    
        text.alignment = TextAnchor.MiddleCenter;
    }
}

#endregion

#region 边缘线和阴影
// 边缘线组件 outline
// 阴影组件 Shadow
#endregion

2. Image: sprite image

Introduction to component properties:
Source Image: Specifies the texture image to be displayed. Note: Image only supports Sprite type pictures.
Color: Image color.
Material: Image rendering material.
Raycast Target: Whether it can perform radiographic inspection.
Image Type: The display type of the image. Different display types will cause Sprite to "fill" the Image component in different ways. Display types include:
(1) Simple: When the size of the Image and Sprite are different, the Sprite will be stretched to be as large as the Image. This operation may cause the image to be deformed. If you do not want the image to be deformed, you can check the PreserveAspect option, and the Sprite will be stretched according to the original width and height ratio of the Sprite.
You can also use the Aspect Ratio Fitter component to maintain a constant aspect ratio.
(2) Sliced: Nine-square grid. During the scaling process, the sprite processed by the nine-square grid will keep the 4 corner slices without scaling, the 4 side slices will only be stretched, and only the middle slice will be scaled. This mode has the Fill Center option checked by default. If it is unchecked, the Image cannot be displayed completely and only the edge image of the slice will be displayed.
(3) Tiled: The floor tiles are tiled. In this mode, the size of the Sprite itself will remain unchanged, and the Sprite will fill the entire Image control like laying floor tiles.
(4) Filled: This mode is generally used for "CD" skill cooling, health bar, blue bar, etc.

void Start()
{
    
    
    #region 简介
    //Image是图像组件
    //是UGUI中用于显示精灵图片的组件
    #endregion

    #region 参数相关

    _imageSimple.sprite = Resources.Load<Sprite>("Character");        // 修改图片的精灵图
    _imageSimple.useSpriteMesh = true;                                // 使用TextureImporter生成的网格显示UI图像
    _imageSimple.preserveAspect = true;                               // 保持恒定宽高比
    _imageSimple.SetNativeSize();                                     // 恢复原图大小

    _imageSliced.fillCenter = false;                                  // 中间部分不显示
    _imageSliced.pixelsPerUnitMultiplier = 1;                         // 每单位像素乘数

    _imageFilled.fillMethod = Image.FillMethod.Horizontal;            // 填充方式
    _imageFilled.fillOrigin = 0;                                      // 填充起始点 

    #endregion
}

3.RawImage: raw image

UV scaling and offset can be set by adjusting UV Rect.
The difference from the Image component:
RawImage is used to display Texture type textures and cannot display Sprite type textures.
When you only have a Texture type texture (such as a picture downloaded from the Internet), you can use Sprite.Create to convert the Texture type texture into a Sprite if necessary. However, this operation is more performance-intensive, so it is recommended to use RawImage for display.

void Start()
{
    
    
    RawImage raw = this.GetComponent<RawImage>();
    raw.texture = Resources.Load<Texture>("image_path");
    raw.uvRect = new Rect(0, 0, 1, 1); 
}

4. Button: button

Interactable: whether it can be interacted with

void Start()
{
    
    
    #region 简介

    //是UGUI中用于处理玩家按钮相关交互的组件

    //默认创建的Button由2个对象组成
    //父对象——Button组件依附对象 同时挂载了一个Image组件 作为按钮背景图
    //子对象——按钮文本(可选)

    #endregion

    #region 代码控制、事件监听
    _btnStartGame.interactable = true;
    _btnStartGame.transition = Selectable.Transition.ColorTint;

    //1.拖脚本
    //2.代码添加
    _btnStartGame.onClick.AddListener(OnBtnStartGameClick);
    #endregion
}

public void OnBtnStartGameClick()
{
    
    
    print("按钮点击,代码添加监听");
}

public void OnBtnStartGameClick2()
{
    
    
    print("按钮点击,通过编辑器拖拽的形式");
}

private void OnDestroy()
{
    
    
    // 清除事件监听
    _btnStartGame.onClick.RemoveListener(OnBtnStartGameClick);
    _btnStartGame.onClick.RemoveAllListeners();
}

5.InputField: input box

[SerializeField]
private InputField _usernameField;

[SerializeField]
private Button _btnPlay;

[SerializeField]
private Text _messageText;

void Start()
{
    
    
    #region InputField简介

    //是UGUI中用于处理玩家文本输入相关交互的组件

    //默认创建的InputField由3个对象组成
    //父对象——InputField组件依附对象 以及 同时在其上挂载了一个Image作为背景图
    //子对象——文本显示组件(必备)、默认显示文本组件(必备)

    print(_usernameField.text);
    #endregion

    #region 监听事件
    //1.拖脚本
    //2.代码添加
    _usernameField.onValueChanged.AddListener((str) =>
    {
    
    
        print("代码监听 输入文本改变:" + str);
    });

    // 输入时按回车
    _usernameField.onSubmit.AddListener((str) =>
    {
    
    
        print("代码监听 提交输入:" + str);
    });

    _usernameField.onEndEdit.AddListener((str) =>
    {
    
    
        print("代码监听 结束输入:" + str);
    });
    #endregion

    _btnPlay.onClick.AddListener(() =>
    {
    
    
        if(!string.IsNullOrEmpty(_usernameField.text))
        {
    
    
            print("点击Play按钮");
        }
        else
        {
    
    
            _messageText.text = "用户名不能为空!";
            _messageText.enabled = true;
        }
    });
}

6. Tooggle: select box

void Start()
{
    
    
    #region Toggle
    
    //是UGUI中用于处理玩家单选框多选框相关交互的组件

    //开关组件 默认是多选框
    //可以通过配合ToggleGroup组件制作为单选框

    //默认创建的Toggle由4个对象组成
    //父对象——Toggle组件依附
    //子对象——背景图(必备)、选中图(必备)、说明文字(可选)

    _toggle.isOn = true;

    _toggleGroup.allowSwitchOff = false;

    //可以遍历提供的迭代器 得到当前处于选中状态的 Toggle
    foreach(Toggle item in _toggleGroup.ActiveToggles())
    {
    
    
        print(item.name + " " + item.isOn);
    }
    //1.拖脚本
    //2.代码添加
    _toggle.onValueChanged.AddListener(ChangValue);

    #endregion
}

public void ChangValue(bool isOn)
{
    
    
    print("代码监听状态改变" + isOn);
}

private void OnDestroy()
{
    
    
    _toggle.onValueChanged.RemoveListener(ChangValue);
    _toggle.onValueChanged.RemoveAllListeners();
}

7.Slider: sliding bar

// 常用于调节音量等功能
void Start()
{
    
    
    _slider.onValueChanged.AddListener(PrintSliderValue);
}

public void PrintSliderValue(float v)
{
    
    
    print("监听 slider 滑动事件,slider value: " + v);
}

8.Dropdown: drop-down menu

[SerializeField]
public Dropdown dd;

private List<string> sceneNames = new List<string>(); // 存储所有场景名称

void Start()
{
    
    
    dd.options.Clear();
    // 获取Asset目录下所有场景名称
    for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
    {
    
    
        string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
        string sceneName = System.IO.Path.GetFileNameWithoutExtension(scenePath);
        sceneNames.Add(sceneName);

        dd.options.Add(new Dropdown.OptionData(sceneName));
    }

    print(dd.value);                         // 打印当前索引值
    print(dd.options[dd.value].text);        // 打印当前索引值对应的显示文本

    dd.onValueChanged.AddListener((index) => {
    
    

        print(sceneNames[index]);
        if(sceneNames[index] != "Main")
        {
    
    
            SceneManager.LoadScene(sceneNames[index]);
        }
    });
}

9.Scrollbar: scroll bar

void Start()
{
    
    
    #region Scrollbar

    //是UGUI中用于处理滚动条相关交互的组件
    //默认创建的Scrollbar由2组对象组成
    //父对象——Scrollbar组件依附的对象
    //子对象——滚动块对象

    //一般情况下我们不会单独使用滚动条 
    //都是配合ScrollView滚动视图来使用
    #endregion

    Scrollbar sb = this.GetComponent<Scrollbar>();
    print(sb.value);    // 打印当前滚动条的值(0-1f)
    print(sb.size);     // 滚动条滑块的大小,其中1表示它填充整个滚动条

    #region 监听事件的两种方式
    //1.拖脚本
    //2.代码添加
    sb.onValueChanged.AddListener((v) => {
    
    
        print("代码监听的函数" + v);
    });
    #endregion
}

public void ChangeValue(float v)
{
    
    
    print(v);
}

10.ScrollView: Scroll view

void Start()
{
    
    
    #region ScrollRect

    // UGUI中用于处理滚动视图相关交互的组件
    // 默认创建的ScrollRect由4组对象组成
    // 父对象——ScrollRect组件依附的对象 还有一个Image组件 最为背景图
    // 子对象
    // Viewport控制滚动视图可视范围和内容显示
    // Scrollbar Horizontal 水平滚动条
    // Scrollbar Vertical 垂直滚动条

    #endregion

    ScrollRect sr = this.GetComponent<ScrollRect>();
    //改变内容的大小 具体可以拖动多少 都是根据它的尺寸来的
    //sr.content.sizeDelta = new Vector2(200, 200);
    sr.normalizedPosition = new Vector2(0, 0.5f);

    #region 监听事件的两种方式
    //1.拖脚本
    //2.代码添加
    sr.onValueChanged.AddListener((vec) =>
    {
    
    
        print(vec);
    });
    #endregion
}

public void ChangeValue(Vector2 v)
{
    
    
    print(v);
}

// 自动导航到指定位置
public static void Nevigate(ScrollRect scrollRect, RectTransform item)
{
    
    
    RectTransform viewport = scrollRect.viewport;
    RectTransform content = scrollRect.content;
    Vector3 itemCurrentLocalPostion = scrollRect.GetComponent<RectTransform>().InverseTransformVector(ConvertLocalPosToWorldPos(item));
    Vector3 itemTargetLocalPos = scrollRect.GetComponent<RectTransform>().InverseTransformVector(ConvertLocalPosToWorldPos(viewport));

    Vector3 diff = itemTargetLocalPos - itemCurrentLocalPostion;
    diff.z = 0.0f;

    var newNormalizedPosition = new Vector2(diff.x / (content.GetComponent<RectTransform>().rect.width - viewport.rect.width),
            diff.y / (content.GetComponent<RectTransform>().rect.height - viewport.rect.height));
    newNormalizedPosition = scrollRect.GetComponent<ScrollRect>().normalizedPosition - newNormalizedPosition;
    newNormalizedPosition.x = Mathf.Clamp01(newNormalizedPosition.x);
    newNormalizedPosition.y = Mathf.Clamp01(newNormalizedPosition.y);
    DOTween.To(() => scrollRect.normalizedPosition, x => scrollRect.normalizedPosition = x, newNormalizedPosition, 0.8f);
}

private static Vector3 ConvertLocalPosToWorldPos(RectTransform target)
{
    
    
    var pivotOffset = new Vector3((0.5f - target.pivot.x) * target.rect.size.x,
            (0.5f - target.pivot.y) * target.rect.size.y, 0f);

    var localPosition = target.localPosition + pivotOffset;
    return target.parent.TransformPoint(localPosition);
}

Guess you like

Origin blog.csdn.net/qq_41044598/article/details/132760588