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);
}
}