编辑模式下,控制对象移动
有时候我们可能会有这样的需求,就是在编辑模式下,控制移动场景中的物体,这里面有两个点要解决:
(1)怎么在编辑模式下运行一个脚本;
(2)怎么有效地响应鼠标按键。
第一个问题可以使用编辑器属性ExecuteInEditMode让脚本在编辑模式也能实时地更新。下面的代码用来控制物体的移动,并且可以在编辑模式下运行:
using UnityEngine; using System.Collections; #if UNITY_EDITOR using UnityEditor; #endif [ExecuteInEditMode] public class MoveComponent : MonoBehaviour { private CharacterController controller; private float speed = 3f; private float rotateSpeed = 50f; public void Init() { controller = transform.GetComponent("CharacterController") as CharacterController; if (controller == null) Debug.Log("CharacterController not add!"); } public void MoveForward() { if (controller == null) return; controller.Move(Time.fixedDeltaTime * transform.forward * speed); } public void MoveBack() { if (controller == null) return; controller.Move(-Time.fixedDeltaTime * transform.forward * speed); } public void TurnLeft() { if (controller == null) return; transform.Rotate(Vector3.up, -Time.fixedDeltaTime * rotateSpeed); } public void TurnRight() { if (controller == null) return; transform.Rotate(Vector3.up, Time.fixedDeltaTime * rotateSpeed); } }
第二个问题的解决方法是使用EditorWindow的OnGUI来响应KeyDown消息,下面的代码通过创建一个测试物体,并为其添加MoveComponent来让其移动:
using UnityEngine; using UnityEditor; using System.Collections; #if UNITY_EDITOR using UnityEditor; #endif public class CameraHelperEditor : EditorWindow { public static CameraHelperEditor window = null; [MenuItem("MyEditor/CameraHelperEditor")] public static void ShowWindow() { window = EditorWindow.GetWindow(typeof(CameraHelperEditor), false, "CameraHelperEditor") as CameraHelperEditor; } private const string Prefab = "Test/Cube"; private GameObject player = null; private MoveComponent moveComp = null; void OnGUI() { if (GUILayout.Button("Init")) { player = GameObject.Instantiate(Resources.Load(Prefab)) as GameObject; player.AddComponent("CharacterController"); moveComp = player.AddComponent("MoveComponent") as MoveComponent; moveComp.Init(); } switch (Event.current.type) { case EventType.keyDown: { if (Event.current.keyCode == KeyCode.W) { Debug.Log(Time.deltaTime); Debug.Log(Time.fixedDeltaTime); moveComp.MoveForward(); } else if (Event.current.keyCode == KeyCode.S) { moveComp.MoveBack(); } else if (Event.current.keyCode == KeyCode.A) { moveComp.TurnLeft(); } else if (Event.current.keyCode == KeyCode.D) { moveComp.TurnRight(); } } break; } } void OnDestroy() { if(player != null) { GameObject.DestroyImmediate(player); player = null; } moveComp = null; } }
可以看到按键消息的响应都是放在OnGUI里面处理的。
对于该问题的解决我相信还有更好的方法,希望伙伴们能够留言给予指点。