Skip to content

Instantly share code, notes, and snippets.

@twobob
Created December 11, 2015 17:03
Show Gist options
  • Save twobob/79b7d1a3c8260733a0f9 to your computer and use it in GitHub Desktop.
Save twobob/79b7d1a3c8260733a0f9 to your computer and use it in GitHub Desktop.
GenerateTextObjectAndPositionDuringRuntime Allows for positioning labels over the world objects, use with LOD to decide draw distances.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GenerateTextObjectAndPositionDuringRuntime : MonoBehaviour
{
public Canvas CanvasToPopulate;
public GameObject TextPrefab;
private GameObject instantiatedPrefab;
private Text textObject;
private RectTransform rectReference;
public int FontSize;
public float LabelVerticalOffset = 0f;
public string textToDisplay;
bool draw = false;
void Start()
{
instantiatedPrefab = Instantiate(TextPrefab);
textObject = instantiatedPrefab.GetComponent<Text>();
rectReference = CanvasToPopulate.GetComponent<RectTransform>();
instantiatedPrefab.transform.SetParent(CanvasToPopulate.transform, false);
textObject.text = textToDisplay;
if (FontSize > 0)
{
textObject.fontSize = FontSize;
}
textObject.enabled = false;
draw = false;
}
void OnBecameInvisible()
{
textObject.enabled = false;
draw = false;
}
void OnBecameVisible()
{
draw = true;
}
// Keep it centralised.
void Update()
{
MoveObject();
}
private void MoveObject()
{
if (!draw)
return;
Vector2 pos = WorldToCanvasPosition.ConvertWorldToCanvasPosition(rectReference, Camera.main, transform.position);
textObject.rectTransform.position = new Vector3(pos.x, pos.y + LabelVerticalOffset);
textObject.enabled = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment