Unity的UGUI鼠标移入显示5秒(笔记)

1层:DurationGroup挂在父物体相当于全局,
2层:第一层子物体用来检测进入,加eventtrigger组件,把第二层子物体拖入。
2层:eventtrigger 两个enter(激活,onEnter) 一个exit(tryclose)。
3层:duration挂在第二层子物体(把duration Group拖入attactGroup) 控制显示,隐藏;

思想:就是主控制要控制只显示一个panel,以免遮挡效果。


代码:
DurationGroup.cs

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


public class DurationGroup : MonoBehaviour 
{
    private SortedList<int,Duration> nestDuration;
    private int count;                                         //count标记。

    void Awake()
    {
        this.nestDuration = new SortedList<int, Duration>();
        this.count = -1;
    }

    public int AddDuration(Duration item)
    {
        this.count++;
        this.nestDuration.Add(this.count,item);
        return this.count;
    }

    public void OnChanged(int indx)
    {
        foreach(var item in this.nestDuration)
        {
            if (item.Key == indx)
                continue;
            if (item.Value.gameObject.activeInHierarchy)
                item.Value.gameObject.SetActive(false);
        }
    }

}

Duration.cs

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

public class Duration : MonoBehaviour 
{
    [SerializeField]
    private float DurationTime = 1.5f;
    private Coroutine closeRoutine;
    [SerializeField]
    private DurationGroup attachGroup = null;
    private int indxInGroup;
    void Start()
    {
        if (this.attachGroup)
        {
            this.indxInGroup = this.attachGroup.AddDuration(this);
            this.attachGroup.OnChanged(this.indxInGroup);
        }
    }

    public void OnPointerEnter()
    {
        if (this.attachGroup)
            this.attachGroup.OnChanged(this.indxInGroup);

        if (this.closeRoutine != null)
            this.StopCoroutine(this.closeRoutine);
    }

    public void TryClose()
    {
        if (this.gameObject.activeInHierarchy)
            this.closeRoutine = StartCoroutine(this.WaitDuration());
    }

    IEnumerator WaitDuration()
    {
        float countTime = 0;
        while (countTime < this.DurationTime)
        {
            yield return new WaitForSecondsRealtime(0.1f);
            countTime += 0.5f;
        }
        this.closeRoutine = null;
        this.gameObject.SetActive(false);
    }

    void OnDisable()
    {
        if (this.closeRoutine != null)
            this.StopCoroutine(this.closeRoutine);
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值