Sometimes we may have the need to control objects in the moving scene in edit mode, which has two points to solve:
(1) How to run a script in edit mode;
(2) How to respond effectively to the mouse button.
The first problem is that you can use the editor properties executeineditmode to let the script update in real time in edit mode. The following code is used to control the movement of an object and can be run in edit mode:
usingUnityengine;usingSystem.Collections;#ifUnity_editorusingUnityeditor;#endif[Executeineditmode] Public classmovecomponent:monobehaviour{PrivateCharactercontroller Controller; Private floatSpeed =3f; Private floatRotatespeed =50f; Public voidInit () {Controller= transform. Getcomponent ("Charactercontroller") asCharactercontroller; if(Controller = =NULL) Debug.Log ("Charactercontroller not add!"); } Public voidMoveforward () {if(Controller = =NULL)return; Controller. Move (Time.fixeddeltatime* Transform.forward *Speed ); } Public voidMoveback () {if(Controller = =NULL)return; Controller. Move (-time.fixeddeltatime * Transform.forward *Speed ); } Public voidTurnLeft () {if(Controller = =NULL)return; Transform. Rotate (Vector3.up,-time.fixeddeltatime *rotatespeed); } Public voidTurnRight () {if(Controller = =NULL)return; Transform. Rotate (vector3.up, Time.fixeddeltatime*rotatespeed); }}
The second solution is to use Editorwindow's Ongui to respond to the KeyDown message, and the following code moves it by creating a test object and adding movecomponent to it:
usingUnityengine;usingUnityeditor;usingSystem.Collections;#ifUnity_editorusingUnityeditor;#endif Public classcamerahelpereditor:editorwindow{ Public StaticCamerahelpereditor window =NULL; [MenuItem ("Myeditor/camerahelpereditor")] Public Static voidShowWindow () {window= Editorwindow.getwindow (typeof(Camerahelpereditor),false,"Camerahelpereditor") asCamerahelpereditor; } Private Const stringPrefab ="Test/cube"; PrivateGameobject player =NULL; PrivateMovecomponent Movecomp =NULL; voidOngui () {if(Guilayout.button ("Init") ) {player= Gameobject.instantiate (Resources.load (Prefab)) asGameobject; Player. AddComponent ("Charactercontroller"); Movecomp= Player. AddComponent ("movecomponent") asmovecomponent; Movecomp.init (); } Switch(Event.current.type) { CaseEventtype.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; } } voidOnDestroy () {if(Player! =NULL) {gameobject.destroyimmediate (player); Player=NULL; } Movecomp=NULL; }}
You can see that the response to the key message is handled in Ongui.
I believe there is a better way to solve this problem, I hope that the partners can leave a message to give advice.
Control object Movement in edit mode