Skip to content

Instantly share code, notes, and snippets.

@tsraveling
Last active June 12, 2020 05:57
Show Gist options
  • Save tsraveling/caa2bd5be6b81c17c1da305b3b426704 to your computer and use it in GitHub Desktop.
Save tsraveling/caa2bd5be6b81c17c1da305b3b426704 to your computer and use it in GitHub Desktop.
Text Log View Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextManager : MonoBehaviour {
public Transform contentView;
public GameObject messagePrefab;
public void addMessage(string text) {
// Add the text object
GameObject textObject = Instantiate(messagePrefab);
Text textComponent = textObject.GetComponent<Text>();
textComponent.text = text;
textObject.transform.SetParent(contentView);
// Scroll to bottom
this.gameObject.GetComponent<ScrollRect>().normalizedPosition = new Vector2(0, 0);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
  1. Create a ScrollRect component on a GameObject and add the above script to it.
  2. Add a Vertical Layout Group component to the content object.
  3. User a Content Size Fitter component to adjust size if needed.
  4. Create a Text GameObject to set as the prefab, and link it to the above script.
  5. Call the addMessage method to add text.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment