Unity协程WaitForSeconds在编辑器和WebGL表现不同问题的解决方法参考

最近做的一个效果让下面为了让下面这种图片生成一个翻页效果(使用ShaderGraph中的FlipBook节点),我通过携程来实现连续翻页。

先是定义一个Coroutine coroutine = null;

然后在一定情况下执行coroutine = StartCoroutine(KeepPreview(texSheet));这样这个协程就可以连续执行起来了,达到通过WaitForSeconds来控制翻页进度的目的。

cs 复制代码
	IEnumerator KeepPreview(TexSheet texSheet)
	{
		if (texSheet)
		{
			float frameRate = Mathf.Abs(texSheet.frameRate);
			if (frameRate < 0.01f)
			{
				yield return null;
			}
			else
			{
				float interval = 1 / frameRate;
				yield return new WaitForSeconds(interval);
				texSheet.UpdateSheetIndex();
			}

			coroutine = StartCoroutine(KeepPreview(texSheet));
		}
	}

本来在编辑器里面是比较正常的,但是发布成WebGL之后效果就有问题。在编辑器里面如果增加翻页的速度(就是增加frameRate的值,帧/秒)确实会出现越转越快的效果,从0到几百都是正常的(当然太快了也没什么意义)但是在WebGL中超过翻页60帧/秒左右感觉速度就没有什么变化了。

我想可能的原因是,在编辑器里面使用WaitForSeconds等待某个时间后,应该是马上就执行后面的内容了,这里是texSheet.UpdateSheetIndex()这个方法。但是在发布成WebGL之后,即使等待的时间到了,也要等到本帧结束了才会执行后面的内容,这应该是即使翻页帧率设置很高翻页效果都和60帧/秒差不多得原因,所以在WebGL环境下的处理方式应该变一下,类似下面代码给出的方法,虽然这个并不是很准确的方法,但视觉上应该也看不出来什么问题吧。

cs 复制代码
	IEnumerator KeepPreview(TexSheet texSheet)
	{
		if (texSheet)
		{
			float frameRate = Mathf.Abs(texSheet.frameRate);
			if (frameRate < 0.01f)
			{
				yield return null;
			}
			else
			{
				float interval = 1 / frameRate;
				yield return new WaitForSeconds(interval);
#if UNITY_EDITOR_WIN
				texSheet.UpdateSheetIndex();
#endif
#if UNITY_WEBGL && !UNITY_EDITOR_WIN
				int updateTimes = (int)(Time.deltaTime / interval);
				if(updateTimes <1) { updateTimes = 1; }
				for(int i = 0; i < updateTimes; i++) { texSheet.UpdateSheetIndex(); }
#endif
			}

			coroutine = StartCoroutine(KeepPreview(texSheet));
		}
	}
相关推荐
AllBlue4 小时前
unity嵌入安卓界面,如何显示状态
android·unity·游戏引擎
tealcwu5 小时前
【Unity技巧】实现在Play时自动保存当前场景
java·unity·游戏引擎
tealcwu6 小时前
【Unity基础】实现Scroll View跟随动态内容滚动
java·unity·游戏引擎
野奔在山外的猫7 小时前
【文档】VSCode 配置 Unity 环境流程
unity
变身缎带16 小时前
Unity中的NetworkManager基于protobuf, Socket-TCP
tcp/ip·unity·游戏引擎
AllBlue1 天前
unity调用安卓方法
android·unity·游戏引擎
郝学胜-神的一滴1 天前
Horse3D游戏引擎研发笔记(十):在QtOpenGL环境下,视图矩阵与投影矩阵(摄像机)带你正式进入三维世界
c++·3d·unity·游戏引擎·godot·图形渲染·unreal engine
AllBlue1 天前
unity导出成安卓工程,集成到安卓显示
android·unity·游戏引擎
Sator11 天前
Unity的FishNet相关知识
网络·unity·游戏引擎
AllBlue1 天前
安卓调用unity中的方法
android·unity·游戏引擎