2

Hey i wondered if you can draw GUI.Label to mouse position, and how you can do it? I'am currently doing the script in Unity C#.

Script layout:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour {

    public bool Hover = false;

    void OnMouseOver()
    {
        Hover = true;
    }

    void OnMouseExit()
    {
        Hover = false;
    }

    void OnGUI()
    {
        if(Hover = true)
        {
        GUI.Label(new Rect(//Transform to mouse positon))
        }
    }
}
  • Note that your code example in your question is not clear to me. If you want to draw at the mouse position, what is the `Hover` bool used for? Hovering over what? Also, the example you provide would not compile due to `if(Hover = true)`, it should be `if (Hover == true)`, but note that `if (Hover)` is the more common and preferred style. – sonnyb May 07 '18 at 12:45
  • The hover == true when you hover over the gameObject with this script attached. And whats the difference between "hover = true" and "hover == true" i used hover = true and it worked? –  May 07 '18 at 13:43
  • `=` is for assignment, and `==` is for comparison. In `if(Hover = true)`, you're setting Hover to true and thus the conditional in the if statement will always return true. [Note that Assignments in C# also return a value for other reasons.](https://stackoverflow.com/q/3807192/5170571) Your compiler or IDE should be warning you about this... – sonnyb May 07 '18 at 14:22

2 Answers2

3

Use Input.mousePosition to create the Rect that is passed to GUI.Label. Note that both of these use screen coordinates but for Input.mousePosition the bottom-left of the screen is (0, 0), and for the Rect used by GUI.Label the top-left of the screen is (0, 0). Thus, you need to flip the y-values like this:

void OnGUI()
{
    var mousePosition = Input.mousePosition;

    float x = mousePosition.x;
    float y = Screen.height - mousePosition.y;
    float width = 200;
    float height = 200;
    var rect = new Rect(x, y, width, height);

    GUI.Label(rect, "Test");
}

For more information, see Unity's documentation on Input.mousePosition and GUI.Label

sonnyb
  • 3,194
  • 2
  • 32
  • 42
-1

You need to convert screen coordinates (mouse position) to GUI ones.

void OnGUI()
{
    if(Hover = true)
    {
        Vector2 screenPos = Event.current.mousePosition;
        Vector2 convertedGUIPos = GUIUtility.ScreenToGUIPoint(screenPos);

        GUI.Label(new Rect(convertedGUIPos.x, convertedGUIPos.y, width, height))
    }
}

I have not actually tested the code though.

More info here: https://docs.unity3d.com/ScriptReference/GUIUtility.ScreenToGUIPoint.html

JackMini36
  • 621
  • 1
  • 5
  • 14
  • Thank you, i tried your could but couldnt get it to work. Then i tried the on you referred to and that one worked. But do you know how i can do "screenPos -10f" –  May 07 '18 at 12:43