[Unity] AnimatorStates中的write defaults详解

来源:互联网 发布:不锈钢开孔器淘宝网 编辑:程序博客网 时间:2024/05/18 00:57

AnimatorState中有一个参数writeDefaultValues,在Inspector中显示的则是Write Defaults

这里写图片描述

官方文档对这个参数的解释是

Whether or not the AnimatorStates writes back the default values for properties that are not animated by its Motion.

这个可有可无的官方解释对读者几乎没有任何价值可言。勾上了writeDefaults的State中不被该motion修改的值都会变为默认值。最关键的一点,这个默认值是什么这里没有给出答案。

在实际的游戏制作过程中,我们会使用对象池来缓存那些暂时用不到但会在之后使用到的游戏体。当我们缓存这些游戏体时,一般会将这些游戏体设置为非活跃状态(GameObject.SetActive(false)),当我们重对象池中取出带有动画的游戏体的时候我们希望这些游戏体拥有和新产生的游戏体一样的状态,但是,结果往往不如人意(如果在游戏体被缓存前SpriteRenderer的透明度改为了0重新取出的时候仍旧是0,而我们希望它是初始的1)。

解释一下什么是我希望发生的:

这里写图片描述

动画状态机里面的State的writeDefaults都被勾选上了,播放完FadeTo的动画之后会进入Default(没有motion的空状态)这个状态,正常来说进入这个状态之后游戏体会重置回默认值。嗯,this works well。但是当FadeTo0退出的时候游戏体被回收,回收的游戏体并不会重置到默认值。再次取出这个游戏体的时候就可能出错。

Unity论坛上看到Unity技术人员这么解释:

1- When the Animator is Initialized, we go through all the clips in the current AnimatorController, and we collect all the animated values of all the clips. It also collects the current value (from the scene) of all those, and saves this as the default value.2- When you play a state with WriteDefaults that doesn't animate a value, the default value is written.

这里的Initialized是有歧义的,经测试应该是解释为Enable。

所以我们问题的关键是回收之前没有重置状态,需要想办法让状态重置。这本来应该是Unity给我们做好的事情,所以并不想自己实现一套writedefaults的功能。该技术人员给出了一种挺好的解决方案

* animator.Crossfade("DefaultPose", 0f); //Force switch to Default Pose State, instant transition* animator.Update(0f); //force transition completion, your object should now be in default pose* go.SetActive(false); //disabled in default pose

解释一下,也就是创建好一个勾上了write defaults的空状态,在回收该游戏体之前先过渡到这个状态,然后调用Animator的Update方法,并传参数0,这样做的意义是让空状态播放一下,让Unity自动为我们做状态重置的工作。

经测试,这个方法很好使!
该讨论的论坛地址是:https://forum.unity3d.com/threads/write-defaults-confusion-bug.392058/

原创粉丝点击