- Home /
Draw Rect in Scene View from EditorWindow
Hi! I'm trying to create a basic level editor. The idea being a simple tile grid and when a user hovers their mouse over a tile in the scene view it will highlight.
I've got the grid to appear perfectly (see screenshot), however I can't figure out at all how I can draw a rect in the scene view. There doesn't seem to be a DrawRect in Handles and DrawRect in Gizmo's apparently cannot be used in OnSceneGUI.
using UnityEngine;
using System.Collections;
using UnityEditor;
public class LevelEditorWindow : EditorWindow {
bool showGrid = true;
Vector2 tiles = new Vector2(6,6);
[MenuItem("Window/Level Editor")]
static void ShowWindow ()
{
GetWindow(typeof(LevelEditorWindow), false, "Level Editor", true);
}
void OnFocus()
{
// Remove and re-add the sceneGUI delegate
SceneView.onSceneGUIDelegate -= this.OnSceneGUI;
SceneView.onSceneGUIDelegate += this.OnSceneGUI;
}
void OnDestroy()
{
SceneView.onSceneGUIDelegate -= this.OnSceneGUI;
}
private void OnGUI()
{
EditorGUILayout.LabelField("Level Editor");
tiles = EditorGUILayout.Vector2Field("Tiles", tiles );
showGrid = EditorGUILayout.Toggle("Show Grid", showGrid);
EditorGUILayout.Space();
if ( GUILayout.Button("Update Scene View") )
{
SceneView.lastActiveSceneView.Repaint();
}
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUILayout.Button("Load Level");
GUILayout.Button("Save Level");
EditorGUILayout.EndHorizontal();
}
void OnSceneGUI(SceneView sceneView)
{
float size_x = tiles.x;
float size_y = tiles.y;
if (showGrid)
{
// Draw all X grid lines
for ( int i = 0; i <= size_x; i++ )
{
// draw a line equal to x and the full height
Handles.DrawLine( new Vector3(i,0,0), new Vector3(i,size_y,0) );
}
// Draw all y grid lines
for ( int i = 0; i <= size_y; i++ )
{
// draw a line equal to x and the full height
Handles.DrawLine( new Vector3(0,i,0), new Vector3(size_x,i,0) );
}
}
// check if mouse is over any tiles
Vector3 mousePosition = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin;
if ( (mousePosition.x > 0 && mousePosition.x < size_x) && (mousePosition.y > 0 && mousePosition.y < size_y) )
{
// mouse is within a tile
int hoverTile_x = (int)Mathf.Floor( mousePosition.x );
int hoverTile_y = (int)Mathf.Floor( mousePosition.y );
// DRAW RECT OVER TILE HERE
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Hold Right-Click + "W" or "S" in Scene Editor not working properly!! 1 Answer
Unity Scene View zooming with scroll-wheel? 5 Answers
Custom scene view in editor window 2 Answers
The scene is empty 4 Answers