I want automaticly generate with my script a GUIText.
At the moment i have a script that work, but you need to add a GuiText with drag and drop at the Inspector.
THE SCRIPT:
using UnityEngine;
using System.Collections;
public class hover : MonoBehaviour
{
public Vector3 offset;
Camera cam;
public string mytext;
public GUIText myGuiText;
void Start ()
{
myGuiText.text = mytext;
myGuiText.enabled = false;
cam = Camera.main;
}
void Update ()
{
myGuiText.transform.position = cam.WorldToViewportPoint (transform.position + offset);
}
void OnMouseEnter ()
{
myGuiText.enabled = true;
}
void OnMouseExit ()
{
myGuiText.enabled = false;
}
}
I need this script to run without using “public GUIText myGuiText”.
Sry if there is somewhere a solution… I found a lot of similar ones. But I dont get it to fix, so it work with my script.
You can use AddComponent(). This code creates a new game object, add a GUIText component, centers the text on the screen (because GUIText uses Viewport coordiantes), and sets the text:
#pragma strict
function Start() {
var go = new GameObject();
go.AddComponent(GUIText);
go.transform.position = Vector3(0.5,0.5,0.0);
go.guiText.text = "Hello World";
}
You can add the component to an existing empty game object, but remember that GUITexts use Viewport coordinates, not world coordinates.