Home > front end >  How do I get the mouse position on a gameobject in unity?
How do I get the mouse position on a gameobject in unity?

Time:10-06

I have currently started a developing a pixel art program in unity. I started with getting the mouse coordinates(x, y) on the ui image(texture) I used the code below but the get the mouse position in world space. I wanna get it in the space of the ui image only. The texture image is 32, 32 pixel wide and tall (x, y respected)

[SerializeField] private Text coordinatesText;
private Vector3 mousePos;
private float mouseX, mouseY;

void Update()
{
    mousePos = Input.mousePosition;
    mouseX = mousePos.x;
    mouseY = mousePos.y;

    coordinatesText.text = (mouseX   ", "   mouseY).ToString();
}

For like, when I hover the mouse on the very bottom left of the texture, which is a ui image, I get 0, 0 and when it's in the very top right, it's 32, 32.

Thanks in advance for your help!

CodePudding user response:

Depending on the Example

  • Related