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));
		}
	}
相关推荐
RReality15 小时前
【Unity UGUI】Toggle / ToggleGroup 与 Dropdown
ui·unity·游戏引擎·图形渲染·材质
雪儿waii16 小时前
Unity 中的 InvokeRepeating 详解
unity·游戏引擎
mxwin16 小时前
Unity Shader 程序化生成:Shader 中的数学宇宙
unity·游戏引擎
雪儿waii18 小时前
Unity 中的 Quaternion(四元数)详解
unity·游戏引擎
RReality18 小时前
【Unity UGUI】ScrollRect 与 Scrollbar 深度用法
unity·游戏引擎
人邮异步社区18 小时前
如何自学游戏引擎的开发?
unity·程序员·游戏引擎
郝学胜-神的一滴19 小时前
[简化版 Games 101] 计算机图形学 05:二维变换下
c++·unity·图形渲染·three.js·opengl·unreal
mxwin1 天前
Unity URP 热更新兼容性:Shader 在 IL2CPP 打包下的注意事项
unity·游戏引擎
mxwin2 天前
Unity shader中TransformWorldToShadowCoord原理解析
unity·游戏引擎·shader
mxwin2 天前
Unity Shader 中 ShadowCaster的作用和疑问
unity·游戏引擎