Display text on prefab click

Hii, im trying to display a msg whenever i’ll click on my prefabs(cubes) in scene.

This is the way i’m trying…

var txt = “Good_work”;

function OnGUI () {
GUI.Label (Rect (300, 300, 10,10), txt);
}

function Update() {
if(Input.GetMouseButtonDown(0))

Camera.main.gameObject.GetComponent(“myGUI”).txt = transform.name;

}

But it displays directly on scene without any click . why isi it so?
and how can i change the text size and font size.?

That’s because you OnGUI is called every time. It kind of depends on your needs. Do you want to

  • display only while the mouse key is hold
  • toggle the display (i.e. click and its visible, click again to disappear)
  • display it for a short period of time, after a click

For the first case you’d have to check the mouse button state before creating the label. i.e

if(Input.GetMouseButton(0) {
   GUI.Label (Rect (300, 300, 10,10), txt);
}

If you want it to toggle, you have to set a bool variable.

var showName = false;
function Update() {
if(Input.GetMouseButtonDown(0))
    showName = !showName;

    Camera.main.gameObject.GetComponent("myGUI").txt = transform.name;

}

void OnGUI() {
  if(showText) {
     GUI.Label (Rect (300, 300, 10,10), txt);
  }
}

And last but not least: display it for a certain amount of time

var timeOfLastClick;
var textDuration = 5.0f;

function Update() {
if(Input.GetMouseButtonDown(0))
    timeOfLastClick = Time.time;

    Camera.main.gameObject.GetComponent("myGUI").txt = transform.name;

}

void OnGUI() {
  if( timeOfLastClick>0  (Time.time-timeOfLastClick) >= textDuration ) {
     GUI.Label (Rect (300, 300, 10,10), txt);
  }
}

But it displays directly on scene without any click . why isi it so?
and how can i change the text size and font size.?

ok, but when i’m getting thsese silly errors, when i’m trying to compile it.
like:…

var txt = “Good_work”;
var timeOfLastClick;
var textDuration = 5.0f;

function Update() {
if(Input.GetMouseButtonDown(0))
{
timeOfLastClick = Time.time;

Camera.main.gameObject.GetComponent(“myGUI”).txt = transform.name;
}
}

void OnGUI() { //Insert a semicolon at the end.
if(( timeOfLastClick>0) (Time.time-timeOfLastClick) >= textDuration ) //Unexpected token: if.
{
GUI.Label (Rect (300, 300, 10,10), txt); // Insert a semicolon at the end.
}
}

why is it so?