代码放在Assets/Editor中:
using UnityEngine;
using UnityEditor;
public class MyWindow : EditorWindow {
const string MenuName = "Atwal Code Snippet";
enum Code_Type
{
input_code,
rigidbody_force_code,
camera_follow
}
static Code_Type type = 0;
static string Code_Name = "";
[MenuItem(MenuName + "/H&V Input")]
public static void Code_HVInput() {
type = Code_Type.input_code;
Code_Name = "H&V Input";
GetWindow(typeof(MyWindow));
}
[MenuItem(MenuName + "/Rigidbody Force")]
public static void Code_RigidbodyForce()
{
type = Code_Type.rigidbody_force_code;
Code_Name = "Rigidbody Force";
GetWindow(typeof(MyWindow));
}
[MenuItem(MenuName + "/Camera Follow")]
public static void Code_CameraFollow()
{
type = Code_Type.camera_follow;
Code_Name = "Camera Follow";
GetWindow(typeof(MyWindow));
}
private void OnGUI()
{
Debug.Log(type);
string content = "";
switch(type)
{
case Code_Type.input_code:
content = @"float moveHorizontal = Input.GetAxis(""Horizontal"");
float moveVertical = Input.GetAxis(""Vertical""); ";
break;
case Code_Type.rigidbody_force_code:
content = @"Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
GetComponent<Rigidbody>().AddForce(movement * speed * Time.deltaTime); ";
break;
case Code_Type.camera_follow:
content = @"public GameObject player;
private Vector3 offset;
// Use this for initialization
void Start () {
//摄像机与跟随物体的初始相对位置
offset = transform.position - player.transform.position;
}
// Update is called once per frame
void LateUpdate () {
//跟随物体的位置加上相对位置
transform.position = player.transform.position + offset;
}";
break;
}
GUILayout.Label(Code_Name + " Code", EditorStyles.boldLabel);
GUILayout.TextArea(content, GUILayout.ExpandHeight(true));
}
}
效果: