Getting clicked tile coordinates from Custom Editor
Hello guys. I'm making a custom editor for my top down 2d game, that, as a part of its functionality, should determine which tile on the grid I click in the Scene view. Converting click coordinates to grid position works flawlessly in my runtime Monobehavior scripts that use main camera.
However when I try to do it from custom editor, the values are off.
Here is my code (the CustomTileInspector script is a Monobehavior attached to the tilemap):
[CustomEditor(typeof(CustomTileInspector))]
public class MyTileEditor : Editor
{
void OnSceneGUI()
{
Event current = Event.current;
if (current.type == EventType.MouseDown && current.button == 1)
{
Vector3 mousePosition = current.mousePosition;
Camera sceneCamera = SceneView.currentDrawingSceneView.camera
;
mousePosition.y = sceneCamera.pixelHeight - mousePosition.y;
mousePosition = sceneCamera.ScreenToWorldPoint(mousePosition);
mousePosition.y = -mousePosition.y;
var Pos = new Vector3Int(Mathf.RoundToInt(mousePosition.x),
Mathf.RoundToInt(mousePosition.y), 0);
Debug.Log
("mouse clicked at "+ Pos.x+","+Pos.y);
}
}
The reported coordinates are off and don't seem to correlate to the Grid properly. Moreover, when I pan the camera the values change, even when I click on the same tile. I'm completely lost and would appreciate any insights on what I am doing wrong.
Answer by blu3drag0n · Nov 02, 2019 at 09:53 AM
using UnityEditor;
using UnityEngine;
[ExecuteInEditMode]
public class GetTilemapCoordinate : MonoBehaviour
{
public Grid grid;
public GetTilemapCoordinate()
{
SceneView.duringSceneGui += GetMousePosition;
}
public void GetMousePosition(SceneView scene)
{
Event e = Event.current;
if (e != null)
{
if (Event.current.type == EventType.MouseDown)
{
Vector3Int position = Vector3Int.FloorToInt(HandleUtility.GUIPointToWorldRay(Event.current.mousePosition).origin);
Vector3Int cellPos = grid.WorldToCell(position);
Debug.Log(cellPos);
}
}
}
}
You are truly a boon to the community, blu3drag0n! Thank you, this works flawlessly.
Your answer
![](https://koobas.hobune.stream/wayback/20220612210014im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Network how to synchronize large tilemap that's made up of bits 0 Answers
Can you use tIDE with Unity? 0 Answers
Get tile from trigger 0 Answers
destructible tilemap, destroying tiles through overlapcircle 1 Answer
Android 2D platformer, low fps 1 Answer