我在测试 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 v3Assets/MeowFramework/Core/Switchable/SwitcherEnum.cs
// ----------------------------------------------
// 作者: 廉价喵
// 创建于: 22/04/2022 18:45
// 最后一次修改于: 26/04/2022 23:05
// 版权所有: CheapMeowStudio
// 描述:
// ----------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector;
using UnityEngine;
namespace MeowFramework.Core.Switchable
{
public class SwitcherEnum : 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 switchableList;
///
/// 可切换变量列表
///
public List SwitchableList
{
get
{
if(switchableList == null)
switchableList = new List();
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;
}
}
}
这下就对了


![[Unity] 战斗系统学习 14:Switchable 3 [Unity] 战斗系统学习 14:Switchable 3](http://www.mshxw.com/aiimages/31/900614.png)
