Unity Editor mouse position to world point
Hi,
I wanna create an editor script. With that, user can add some assets to the scene by clicking on the screen. (NOT IN GAME, IN EDITOR) To do this, I need to find the mouse position from SCENE CAMERA to world point. I did some research and made a POC. I pass the best answer I could found. But the the problem is, it is not working, it looks like an exponential offset happening to the world position. I don't know what the problem is and there is no clear answer I could found in the internet. Could some one help me?
Here is my Editor Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(LevelManager))]
public class LevelManagerEditor : Editor {
SerializedProperty position;
void OnEnable()
{
position = this.serializedObject.FindProperty("position");
}
public void OnSceneGUI(){
Vector2 mousePos = Event.current.mousePosition;
mousePos.y = Camera.current.pixelHeight - mousePos.y;
Vector3 worldPosition = Camera.current.ScreenToWorldPoint(mousePos);
worldPosition.z = 0;
position.vector3Value = worldPosition;
serializedObject.ApplyModifiedProperties();
}
}
Here is Game Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelManager : MonoBehaviour {
public Vector3 position;
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawCube(position, Vector3.one * .5f);
}
}
Answer by hazarartuner · Jun 04, 2017 at 04:31 PM
I found the solution. It was 2D game and I found the answer in this post: http://www.yudiz.com/making-a-basic-2d-tile-map-editor-using-a-custom-inspector/
TLDR:
I get the position by: HandleUtility.GUIPointToWorldRay (Event.current.mousePosition).origin and set "z" coordinate to 0.
Your answer
![](https://koobas.hobune.stream/wayback/20220612123451im_/https://answers.unity.com/themes/thub/images/avi.jpg)