![00c05a1d5da27e35a00a29a37eb79eed.png](https://i-blog.csdnimg.cn/blog_migrate/4b3c4854bd8e5d08d7a7c805d0c2b8eb.jpeg)
前言
读Building a Level Editor in Unity的笔记
自己做编辑器的缘由
代码结构
代码的主要文件如下图
![e112fff70533bd725e0902e14f2a0448.png](https://i-blog.csdnimg.cn/blog_migrate/426f313cee40a197298689d2b09b00ac.png)
EditorObject 和 *LevelEditor 脚本处理场景数据。EditorObject *包含单个场景物体的数据, *LevelEditor *则持有整个关卡的数据。
当保存关卡时,所有包含了*EditorObject 的物体将在LevelEditor 中标记,然后保存在Json中(个人比较喜欢XML)。ManagerScript *是整个编辑器的控制中心, 处理了UI,保存,检查等逻辑。
*CameraMove *和 *MouseScript *脚本是用来处理输入的, 比如放置和销毁物体以及调整相机视角。
- EditorObject
一个组件,放在要编辑的场景物体上;为了序列化使用了一个data结构体,没什么特别的。
using System;
using UnityEngine;
public class EditorObject : MonoBehaviour
{
public enum ObjectType { Cylinder, Cube, Sphere, Player};
[Serializable]
public struct Data
{
public Vector3 pos;
public Quaternion rot;
public ObjectType objectType;
}
public Data data;
}
- LevelEditor
存了这个关卡所有的Data
using System.Collections.Generic;
using System;
[Serializable]
public class LevelEditor
{
public List<EditorObject.Data> editorObjects;
}
- CameraMove
(我用不着)
using UnityEngine;
using UnityEngine.UI;
public class CameraMove : MonoBehaviour
{
public Slider cameraSpeedSlide;
public ManagerScript ms;
private float xAxis;
private float yAxis;
private float zoom;
private Camera cam;
// Start is called before the first frame update
void Start()
{
cam = GetComponent<Camera>(); // get the camera component for later use
}
// Update is called once per frame
void Update()
{
if (ms.saveLoadMenuOpen == false) // if no save or load menus are open.
{
xAxis = Input.GetAxis("Horizontal"); // get user input
yAxis = Input.GetAxis("Vertical");
zoom = Input.GetAxis("Mouse ScrollWheel") * 10;
// move camera based on info from xAxis and yAxis
transform.Translate(new Vector3(xAxis * -cameraSpeedSlide.value, yAxis * -cameraSpeedSlide.value, 0.0f));
transform.position = new Vector3(
Mathf.Clamp(transform.position.x, -20, 20),
Mathf.Clamp(transform.position.y, 20, 20),
Mathf.Clamp(transform.position.z, -20, 20)); // limit camera movement to -20 min, 20 max. Y value remains 20.
//change camera's orthographic size to create zooming in and out. Can only be between -25 and -5.
if (zoom < 0 && cam.orthographicSize >= -25)
cam.orthographicSize -= zoom * -cameraSpeedSlide.value;
if (zoom > 0 && cam.orthographicSize <= -5)
cam.orthographicSize += zoom * cameraSpeedSlide.value;
}
}
}
- MouseScript
我也不需要这个就没仔细看,用编辑器的相应也许更好
- ManagerScript
读写序列化后的场景,生成场景,最重要的部分。
接下来我会实现一个自己的版本(和MC类似的网格编辑器)