DailyDemo:日常用到的方法记录

6 阅读2分钟

概述(Overview)

DailyDemo 是一个用于演示 Unity 中常用交互事件、异步流程控制及 DOTween 动画的示例类。

主要功能包括:

  • 2D UI 与 3D 物体的 EventTrigger 事件绑定
  • 使用 UniTask 实现的异步等待与流程控制
  • DOTween 常用动画示例(颜色渐变、位移、旋转、缩放等)
  • 按钮点击异步等待、事件监听扩展方法等实用模式

适用于快速验证交互逻辑、UI/3D 事件响应、异步流程编排的开发场景。


方法一览(API Index)

方法名访问级别异步返回类型主要功能备注
InteractionUIprivatevoid为 2D Image 添加 EventTrigger 交互事件鼠标进入/退出监听
Interaction3Dprivatevoid为 3D GameObject 添加 EventTrigger 事件需相机挂载 PhysicsRaycaster
ProcessTestprivate是(内部)void演示多段异步按钮点击等待与流程控制通过静态委托 EnterFlowAsync 暴露
DemoprivateUniTask综合演示 2D/3D 事件触发与异步等待包含 OnClickAsync 扩展用法
SetBgColorprivateTask背景颜色渐变 + 文字显示/隐藏(已注释)DOTween DOColor 示例
StartTransitionprivatevoid物体材质颜色渐变(已注释)DOTween DOColor 示例
SetHightprivatevoidCube 高度(Z 轴缩放)匀速动画(已注释)DOTween DOFloat + Scale 示例
MoveAndRotateCameraprivatevoid相机位置 + 旋转平滑动画(已注释)DOTween DOMove + DORotate 示例

方法详情

InteractionUI

为 2D UI Image 添加鼠标进入/退出事件监听。

/// <summary>
/// 给 2D UI Image 添加 EventTrigger 事件(PointerEnter / PointerExit)
/// 直接将 Image 组件拖入 public Image ima 字段即可使用
/// </summary>
private void InteractionUI()
{
    if (!ima.GetComponent<EventTrigger>())
    {
        ima.gameObject.AddComponent<EventTrigger>();
    }

    ima.GetComponent<EventTrigger>()
        .AddListener(EventTriggerType.PointerEnter, _ => { Debug.Log($"Enter {ima.name}"); });

    ima.GetComponent<EventTrigger>()
        .AddListener(EventTriggerType.PointerExit, _ => { Debug.Log($"Exit {ima.name}"); });
}

依赖:UnityEngine.EventSystems, UnityEngine.UI


Interaction3D

为 3D 对象添加鼠标进入/退出事件监听。

/// <summary>
/// 给 3D GameObject 添加 EventTrigger 事件(PointerEnter / PointerExit)
/// 前提:Main Camera 需要挂载 PhysicsRaycaster 组件
/// </summary>
private void Interaction3D()
{
    if (!go.GetComponent<EventTrigger>())
    {
        go.AddComponent<EventTrigger>();
    }

    go.GetComponent<EventTrigger>()
        .AddListener(EventTriggerType.PointerEnter, _ => { Debug.Log($"Enter {go.name}"); });

    go.GetComponent<EventTrigger>()
        .AddListener(EventTriggerType.PointerExit, _ => { Debug.Log($"Exit {go.name}"); });
}

依赖:相机需挂载 PhysicsRaycaster


ProcessTest

演示多阶段异步流程控制,常用于引导、教学、步骤等待等场景。

public static Func<string, UniTask> EnterFlowAsync;

public Button btn;

/// <summary>
/// 初始化异步流程入口,通常在 Start 中调用
/// 通过静态委托 EnterFlowAsync 暴露给外部调用
/// </summary>
void ProcessTest()
{
    EnterFlowAsync = async (value) =>
    {
        await btn.OnClickAsync();
        Debug.Log($"第一次开始 {value}");

        await UniTask.Delay(TimeSpan.FromSeconds(1));
        await btn.OnClickAsync();
        Debug.Log($"第二次开始 {value}");

        async UniTask Process()
        {
            await btn.OnClickAsync();
            Debug.Log($"第三次开始 {value}");
            await UniTask.Delay(TimeSpan.FromSeconds(3));
            Debug.Log($"延时 3s 结束");
        }

        await Process();

        await btn.OnClickAsync();
        Debug.Log($"第四次开始 {value}");
    };
}

典型用法(在其他脚本中):

await DailyDemo.EnterFlowAsync("实验流程");

依赖:Cysharp.Threading.Tasks, 自定义扩展方法 OnClickAsync


Demo

综合演示 2D/3D 交互事件监听与异步点击等待。

private async UniTask Demo(CancellationToken token)
{
    // 3D 物体事件监听示例
    go.OnEventTriggerAddListener(() => Debug.Log("enter"), EventTriggerType.PointerEnter);
    go.OnEventTriggerAddListener(() => Debug.Log("exit"),  EventTriggerType.PointerExit);
    go.OnEventTriggerAddListener(() => Debug.Log("click"));

    // 2D Image 事件监听示例
    ima.OnEventTriggerAddListener(_ => Debug.Log($"click={ima.name}"));
    ima.OnEventTriggerAddListener(_ => Debug.Log($"enter={ima.name}"), EventTriggerType.PointerEnter);
    ima.OnEventTriggerAddListener(_ => Debug.Log($"exit={ima.name}"),  EventTriggerType.PointerExit);

    // 异步等待点击
    await go.OnClickAsync3D(token);
    Debug.Log(123);

    await ima.OnClickAsync2D(token);
    Debug.Log(456);
}

依赖:自定义扩展方法 OnEventTriggerAddListener、OnClickAsync3D、OnClickAsync2D


已注释但具有参考价值的动画示例

SetBgColor(背景渐变 + 文字显示)

// async Task SetBgColor()
// {
//     await UniTask.Delay(TimeSpan.FromSeconds(1));
//     goDict["背景"].GetComponent<Image>().DOColor(Color.white, 1);
//     await UniTask.Delay(TimeSpan.FromSeconds(1));
//     goDict["背景文本"].SetActive(true);
//     goDict["背景文本"].GetComponent<Text>().text = "……";
//     await UniTask.Delay(TimeSpan.FromSeconds(5));
//     goDict["背景文本"].SetActive(false);
//     goDict["背景"].GetComponent<Image>().DOColor(new Color(1,1,1,0), 1);
// }

StartTransition(材质颜色渐变)

// private void StartTransition()
// {
//     rend.material.DOColor(targetMaterial.color, transitionDuration);
// }

SetHight(物体高度匀速变化)

// private void SetHight()
// {
//     var current = cube.localScale.z;
//     DOTween.To(() => current, x => {
//         var s = cube.localScale; s.z = x; cube.localScale = s;
//     }, targetHeight, duration).SetEase(Ease.Linear);
// }

MoveAndRotateCamera(相机平滑移动 + 旋转)

// private void MoveAndRotateCamera()
// {
//     camera.transform.DOMove(target.position, duration);
//     camera.transform.DORotate(target.rotation.eulerAngles, duration);
// }