鼠标悬停在对象上时显示GUI按钮

时间:2013-11-26 19:53:30

标签: c# unity3d

我的屏幕上已经有这个播放器了。我希望,只要鼠标悬停在对象上,GUI按钮就会显示出来(如工具提示)。我尝试了下面的代码,但当我将鼠标悬停在对象上时,按钮没有显示出来。这是我的代码:

void OnMouseEnter()

    {

        Rect buttonRect = new Rect(250, Screen.height - buttonHeight, textInfoPlayerButtonWidth, textInfoPlayerButtonHeight);



        if (GameManager.instance.currentPlayerIndex == 0) (the object)

        {

            if (GUI.Button(buttonRect, "This is player 1"))

            {



            }

        }

    }

我想这样: enter image description here

但是我希望它能够显示该字符上的GUI悬停按钮,而不是在选择字符时。

谢谢

2 个答案:

答案 0 :(得分:0)

您可能希望尝试使用 MouseHover 事件。当鼠标悬停在给定对象上时, MouseEnter 将被称为 。另一方面, MouseHover 仅在鼠标停留在给定对象上超过X时间时触发(虽然我不确定这需要多长时间)。

(另外,我不确定你是否在你的例子中正确设置了你的事件处理程序作为 MouseEnter 事件的订阅者,但这里有一个解释它的链接:{{3 }})

然后您可以显示您的Rect对象:

Component myComponent.MouseHover += new EventHandler(OnMouseHover);

...

void OnMouseHover(object sender, EventArgs e)
{
    Rect buttonRect = new Rect(250, Screen.height - buttonHeight, textInfoPlayerButtonWidth, textInfoPlayerButtonHeight);

    if (GameManager.instance.currentPlayerIndex == 0) (the object)
    {
        if (GUI.Button(buttonRect, "This is player 1"))
        {
            //accomplish whatever you had wanted here
        }
    }
}

答案 1 :(得分:0)

如果对象是一个3d对象,那么我知道的唯一方法是找出鼠标是否悬停在该对象上方是光线投射。这是一个简单的例子:

void Update() 
{
    Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray,out hit) && hit.collider.gameObject == playerObject)
    {
        //Do something here
    }
}

OR

void Update() 
{
    Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray,out hit) && hit.collider.gameObject.name == "myPlayerObjectName")
    {
        //Do something here
    }
}

然而,这可能会非常密集,因此您可能希望在定时器或其他东西上运行它,例如每5秒钟一次,具体取决于您的需求。

相关问题