1. Bug:协程阻塞游戏主线程
我在测试 Switchable 的时候发现我的过渡并没有达到应有的效果,几乎是瞬间就从起点值到达了终点值,没有平滑 我把平滑时间延长了之后发现游戏有明显的阻塞,这和我对协程的第一印象相悖
原代码
使用 IEnumerator 函数用于协程
private IEnumerator ModeTransition(T mode)
{
float time = ModeTransitionTime;
while(time > 0)
{
time -= Time.deltaTime;
Debug.Log(time);
foreach (ISwitchable switchable in switchableList)
{
switchable.SwitchValue(mode);
}
}
yield return null;
}
协程启动方式
[ShowInInspector]
[Tooltip("行动模式")]
private T mode;
public T Mode
{
get => mode;
set
{
if (owner != null)
{
if (switchValueCoroutine != null)
owner.StopCoroutine(switchValueCoroutine);
switchValueCoroutine = owner.StartCoroutine(ModeTransition(value));
mode = value;
}
}
}
后来我悟了……原来是还是需要 yield return
2. SwitcherEnum v3
Assets/MeowFramework/Core/Switchable/SwitcherEnum.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector;
using UnityEngine;
namespace MeowFramework.Core.Switchable
{
public class SwitcherEnum<T> : ISwitcher where T: Enum
{
private SerializedMonoBehaviour owner;
public SerializedMonoBehaviour Owner
{
set => owner = value;
}
[ShowInInspector]
[Tooltip("行动模式")]
private T mode;
public T Mode
{
get => mode;
set
{
if (owner != null)
{
if (switchValueCoroutine != null)
owner.StopCoroutine(switchValueCoroutine);
switchValueCoroutine = owner.StartCoroutine(ModeTransition(value));
mode = value;
}
}
}
[Tooltip("切换模式的过渡时间")]
public float ModeTransitionTime = 1f;
private List<ISwitchable> switchableList;
public List<ISwitchable> SwitchableList
{
get
{
if(switchableList == null)
switchableList = new List<ISwitchable>();
return switchableList;
}
}
private Coroutine switchValueCoroutine;
private IEnumerator ModeTransition(T mode)
{
float time = ModeTransitionTime;
while(time > 0)
{
time -= Time.deltaTime;
foreach (ISwitchable switchable in switchableList)
{
switchable.SwitchValue(mode);
}
yield return new WaitForSeconds(Time.deltaTime);
}
yield return null;
}
}
}
这下就对了
|