- Home /
How to get a pop-up window floating next to a gameobject?
I'm trying to get a GUI popup window with selectable options to pop up next to NPCs when you mouse over them and press e and be used as a way to talk to them. Something like Skyrim I suppose. I've been away from programming a while and I've remembered how to get the mouse over working but not the GUI stuff. I know it's not much but here is what I have so far:
using UnityEngine;
using System.Collections;
public class TalkingTestScript : MonoBehaviour {
public Rect windowRect = new Rect(0,0,0,0);
public int lookingat = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseOver() {
lookingat = 1;
//does GUI stuff go here or later?
}
}
I've been playing around with the GUI stuff from the manual but I'm not getting very far and I'm not sure what to do instead. Thanks a lot for any help!
Answer by TonyLi · Jun 11, 2013 at 01:41 AM
As a first pass, add another method called OnGUI(). GUI controls use screen coordinates. You'll probably want to make the GUI appear near the NPC. To do this, you can use use Camera.WorldToScreenPoint():
void OnGUI() {
// Bail out immediately if not moused over:
if (!lookingat) return;
// Get the screen position of the NPC's origin:
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
// Define a 100x100 pixel rect going up and to the right:
Rect menuRect = new Rect(screenPos.x, screenPos.y - 100, 100, 100);
// Draw a label in the rect:
GUI.Label(menuRect, "Menu Goes Here");
}
As a first pass, just try to get a label or a button to pop up, using something like the code above. (Warning: I didn't test it; I just typed it into the answer box.)
Then you swap in a GUI.Window. Windows are more complicated, so just make sure you get basic GUI elements showing where you want first. Info on windows are at the bottom of this page: http://docs.unity3d.com/Documentation/Components/gui-Controls.html
Down the road, you may want to put the GUI stuff in a separate script that you enable only when the player is mousing over the NPC. But I recommend just getting it working now, and read up on GUI optimization later.
Your answer
Follow this Question
Related Questions
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Distribute terrain in zones 3 Answers
How can I clear a textbox and repeat the text with my effect? 0 Answers
Multiple Cars not working 1 Answer
How to dynamically change the text in Unity(Augmented Reality + NYARtoolkit(C#)) ? 0 Answers