在做道具配置的時(shí)候谒亦,想要實(shí)現(xiàn)在編輯器內(nèi)有一個(gè)和攝像機(jī)可視范圍同樣大小的矩形框鹿响,用來(lái)告訴我道具放置的邊界在哪里周伦,于是想要實(shí)現(xiàn)在scene窗口畫矩形的一個(gè)效果郑现,Unity的Gizmo可以實(shí)現(xiàn)類似的效果湃崩。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class ItemGroupGenerator
{
//ItemGroup是一個(gè)空的MonoBehaviour, 用于掛在想要顯示Gizmo的物體上
[DrawGizmo(GizmoType.NonSelected | GizmoType.Active | GizmoType.InSelectionHierarchy)]
static void DrawItemGizmoType(ItemGroup gameObject, GizmoType gizmoType)
{
var transform = gameObject.transform;
//根據(jù)選中的狀態(tài)做差異化實(shí)驗(yàn)
/*
//該物體沒(méi)有選中為綠色
if ((gizmoType & GizmoType.NonSelected) != 0)
{
Gizmos.DrawWireCube(transform.position, Vector3.one);
}
//該物體選中時(shí)為紅色
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);
}
}
效果圖如下: