在做道具配置的时候,想要实现在编辑器内有一个和摄像机可视范围同样大小的矩形框,用来告诉我道具放置的边界在哪里,于是想要实现在scene窗口画矩形的一个效果,Unity的Gizmo可以实现类似的效果。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class ItemGroupGenerator
{
//ItemGroup是一个空的MonoBehaviour, 用于挂在想要显示Gizmo的物体上
[DrawGizmo(GizmoType.NonSelected | GizmoType.Active | GizmoType.InSelectionHierarchy)]
static void DrawItemGizmoType(ItemGroup gameObject, GizmoType gizmoType)
{
var transform = gameObject.transform;
//根据选中的状态做差异化实验
/*
//该物体没有选中为绿色
if ((gizmoType & GizmoType.NonSelected) != 0)
{
Gizmos.DrawWireCube(transform.position, Vector3.one);
}
//该物体选中时为红色
if ((gizmoType & GizmoType.Active) != 0)
{
Gizmos.DrawWireCube(transform.position, Vector3.one);
}
//该物体选中或者该物体的父物体被选中
if ((gizmoType & GizmoType.InSelectionHierarchy) !=0 )
{
Gizmos.DrawWireSphere(transform.position, 0.5f);
}
*/
Vector3 cornerPos = Camera.main.ViewportToWorldPoint(new Vector3(1f, 1f, Mathf.Abs(-Camera.main.transform.position.z)));
Vector3 leftUp = new Vector3(transform.position.x - cornerPos.x, transform.position.y + cornerPos.y, 0);
Vector3 rightUp = new Vector3(transform.position.x + cornerPos.x, transform.position.y + cornerPos.y, 0);
Vector3 leftDown = new Vector3(transform.position.x - cornerPos.x, transform.position.y - cornerPos.y, 0);
Vector3 rightDown = new Vector3(transform.position.x + cornerPos.x, transform.position.y - cornerPos.y, 0);
Gizmos.color = Color.green;
Gizmos.DrawLine(leftUp, rightUp);
Gizmos.DrawLine(leftUp, leftDown);
Gizmos.DrawLine(leftDown, rightDown);
Gizmos.DrawLine(rightUp, rightDown);
}
}
效果图如下: