Unity | 手把手教你实现按钮 loading 状态

4,538 阅读2分钟

效果展示与功能描述

先看效果:

功能描述:当处于加载状态时,按钮上出现旋转的 loading 图标,且按钮不可点击;结束加载状态后,loading 图标消失,且按钮可点击。

实现方案与代码示例

  1. 创建 loadingIcon 对象

工具栏 -> GameObject -> UI -> Image,创建一个具有 Image 组件的游戏对象。

调整 Rect Transform 组件中的 width、height 来调整图标的大小。在 Image 组件中,修改 Source Image 为 loading 图标。

*对象层级怎么放都行,也可以将 loadingIcon 作为 Button 的子对象。脚本绑定时只需要关注「将具有 Button 组件的对象拖到 button 变量,将 loadingIcon 对象拖到 loadingIcon 变量」这个对应关系即可(后面展开介绍)。

  1. 创建脚本

顶部工具栏 Assets -> Create -> C# Script,命名为 ButtonController.cs

  1. 编写脚本

思路:

  • 支持两个方法,一个是 loading,启用按钮 loading 状态;另一个是 StopLoading,关闭按钮 loading 状态。
  • Loading 方法中,将按钮的可交互状态设为 true,将 loading 图像设置为激活状态,同时设置 loading 状态变量为 true,用于在组件 Update 钩子中执行旋转逻辑。
  • StopLoading 方法同上,状态相反,这里不展开介绍。
  • Update 生命周期中,对 loadingIcon 进行旋转

示例代码:

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

public class ButtonController : MonoBehaviour
{
    public GameObject button, loadingIcon;
    bool _loading = false;
    
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        if(_loading) {
            loadingIcon.transform.Rotate(0.0f, 0.0f, 1.0f, Space.World);
        }
    }

    public void Loading() {
        button.GetComponent<Button>().interactable = false;
        loadingIcon.SetActive(true);
        _loading = true;
    }

    public void StopLoading() {
        button.GetComponent<Button>().interactable = true;
        loadingIcon.SetActive(false);
        _loading = false;
    }
}

4. 将脚本拖拽到对象上,再把 button 对象和 loadingIcon 对象拖入变量区域即可

将脚本拖拽到对象上:(脚本放在哪个对象上都可以,跟上边强调的一样,只需要关注脚本中绑定的对象正确即可)

把 button 对象和 loadingIcon 对象拖入变量区域: