- Home /
Editor mousePosition changing when key is pressed
I am trying to instantiate an a gameObject on my grid when I press 'a'. When 'a' is pressed it creates a ray from where the mouse is on the sceneview and gets where it hits the xz-plane. This is the point I wish to place the object. The log shows it is correct when I am moving my mouse over the grid but when I press 'a' it seems to change the point to a different location. Anyone know whats going wrong with this code?
void GridUpdate(SceneView sceneview) {
Event e = Event.current;
Ray r = sceneview.camera.ScreenPointToRay(new Vector3(e.mousePosition.x, -e.mousePosition.y + sceneview.camera.pixelHeight,0));
Plane p = new Plane(new Vector3(0,0,0), new Vector3(0,0,1), new Vector3(1,0,1));
float d=0f;
p.Raycast(r,out d);
Vector3 pPoint = r.GetPoint(d);
//Debug.Log(pPoint); // This gives correct point until 'a' is pressed
if (e.isKey && e.character == 'a') {
Object prefab = PrefabUtility.GetPrefabParent(Selection.activeGameObject);
if (prefab) {
obj = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
Vector3 aligned = new Vector3(Mathf.Floor(pPoint.x/map.space) + map.space/2.0f,0,
Mathf.Floor(pPoint.z/map.space) + map.space/2.0f);
obj.transform.parent = map.transform;
obj.transform.position = aligned;
}
}
}
After playing around with this. It seems the mousePosition.x
is correct and its just something to do with -e.mousePosition.y + sceneview.camera.pixelHeight
. I avoided this problem by using if (Event.current.type == EventType.mouseDown)
ins$$anonymous$$d.
why is it:
Ray r = sceneview.camera.ScreenPointToRay(new Vector3(e.mousePosition.x, -e.mousePosition.y + sceneview.camera.pixelHeight,0));
why isn't:
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
I don't get it why scene view as in scene you won't get running code unless you have run in backeground
and why are you using event for it use update and not OnGUI
is there a special reason for using OnGUI?
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
Two reason for not using this are the main camera is not the camera the editor scene windows use and input class only works in play. To get it to work in the editor you need to use Camera.current or the correct sceneview camera and use Event.current to get input.
Your answer
Follow this Question
Related Questions
2017.3 Editor frame drop and movement reaction speed [ISSUE] 1 Answer
Debug Console doesnt show up 7 Answers
Is there a way to create a folder hierarchy view in the editor? 1 Answer
Creating a custom script that extends other scripts in Editor 1 Answer
Using Camera screen point to ray for look rotation problem... 1 Answer