【Unity】优化 if else 和 Switch Case
优化 if else 和 Switch Case
z
大量的if else 和 Switch Case会造成代码冗余且消耗性能,可以借用如下方法优化
-
使用字典进行优化
- 方法优化:
//注册字典,通过Action作为值,然后进行回调 private Dictionary<int, Action<CharacterEntity>> animationActions = new Dictionary<int, Action<CharacterEntity>>() { { 0, (character) => character.animator.SetTurnUp() }, { 1, (character) => character.animator.SetTurnDown() }, { 2, (character) => character.animator.SetTurnRight() }, { 3, (character) => character.animator.SetTurnLeft() } }; /****************调用方法****************/ //通过对字典判空 //传参执行回调 private void UpdatePlayerAnimation(CharacterEntity character, int id) { if (animationActions.TryGetValue(id, out var action)) { action(character); } }
-
使用数组进行优化:
- 优化坐标:
//创建坐标数组 private Vector3[] _positionOffsets = new Vector3[] { new Vector3(0, 1f, 0), new Vector3(0, -0.2f, 0), new Vector3(-0.7f, 0, 0), new Vector3(0.7f, 0, 0) }; //直接通过id调用即可 transform.position = pos + _positionOffsets[id];
原文地址:https://blog.csdn.net/Xz616/article/details/135514139
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!