- Home /
(Unity2D) How to make a GUI text over a specific object?
Pretty much, this question is how to make a GUI. I have never done it before, so I am asking now (looked on the internet, didn't understand anything, so now I am here).
Anyway, I have a Sprite with a script (Tute1) attached to it. This is not the player, however. Tute1: using UnityEngine; using System.Collections;
public class Tute1 : MonoBehaviour {
// Use this for initialization
public float Distance;
public float Range = 15.0f;
public Transform target;
public bool talk = false;
void Update(){
Distance = Vector3.Distance (transform.position, target.position);
if (Distance < Range) {
talk = true;
}
if (talk) {
//Gui text
}
}
}
In the last if statement, I am going to have dialogue over the Sprite (var target is the set to player in the inspector). How can I make it? I have heard of OnGUI, but don't know how to use it in this circumstance. And how can I make the text right above the Sprite? If I must, I can post an image of the scene
Thanks for anything!
Answer by andrew-lukasik · Jul 05, 2014 at 08:27 AM
Proper place for GUI related code isn't inside Update(){} but inside OnGUI(){}. In the same time notice that Update is being called only once per frame while OnGUI due to it's technical nature is executed many times in every frame. So things like this Vector3.Distance() you want to keep in Update since you need only one measurement/frame.
void Update () {
Distance = Vector3.Distance (transform.position, target.position);
if (Distance < Range) {talk = true;}
}
void OnGUI(){
if (talk) {
Vector3 getPixelPos = Camera.main.WorldToScreenPoint( target.position );
getPixelPos.y = Screen.height - getPixelPos.y;
GUI.Label( new Rect(getPixelPos.x,getPixelPos.y,200f,100f) , "It's Me, Mario! :D");
}
}
If you want to offset this position by some world position do it like this:
Vector3 getPixelPos = Camera.main.WorldToScreenPoint( target.position + new Vector3(0f,1f,0f) );//<< WorldToScreenPoint( position + offset )
and by screen pixel value like this:
Vector3 getPixelPos = Camera.main.WorldToScreenPoint( target.position );
getPixelPos.y = Screen.height - getPixelPos.y;
// ^^^^ calculate base position first, then:
getPixelPos.x += 30f;//<<<< offset x
getPixelPos.y -= 40f;//<<<< offset y
Your answer
Follow this Question
Related Questions
Place UI element on pointer up position. 1 Answer
Unlocking & "Equipping" Colors onto Sprites with c# 2 Answers
Multiple Cars not working 1 Answer
urgent, pls help. Selection through keyinput in Canvas 2 Answers
Space opening main menu (undesired) 0 Answers