#62 - Overhead Lines for Character Unity

Date: 2019-05-25 12:00 - c#

Displays lines over an object in Unity. You need to setup a line prefab which is a game object with a RawImage and Text to make this work.

// OverHeadLines.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public partial class OverHeadLines : MonoBehaviour {

	public GameObject overHeadLinePrefab;

	[SerializeField]
	private List<Line> _lines = new List<Line>();
	public List<Line> Lines {
		get { return _lines; }
	}

	void Start () {
		ForceRebuildLines();
	}

	public Line AddLine(Line line) {
		_lines.Add(line);
		ForceRebuildLines();
		return line;
	}
	public void RemoveLine(Line line) {
		int index = _lines.IndexOf(line);
		if (index != -1) {
			Destroy(transform.GetChild(index).gameObject);
			_lines.RemoveAt(index);
		}
	}

	public void RebuildLine(Line line) {
		int index = _lines.IndexOf(line);
		if (index != -1) {
			UpdateLineObject(transform.GetChild(index).gameObject, line);
		}
	}

	public void ForceRebuildLines() {
		_lines.Sort();

		for (int i = transform.childCount - 1; i >= 0; i--)
			Destroy(transform.GetChild(i).gameObject);

		foreach (Line line in _lines) {
			GameObject lineObj = GameObject.Instantiate(overHeadLinePrefab, transform);
			UpdateLineObject(lineObj, line);
		}
	}

	private void UpdateLineObject(GameObject lineObj, Line line) {
		RawImage lineImage = lineObj.GetComponentInChildren<RawImage>();
		Text lineText = lineObj.GetComponentInChildren<Text>();
		lineImage.gameObject.SetActive(line.icon != null);
		lineImage.texture = line.icon;
		lineText.text = line.text;
		LayoutRebuilder.ForceRebuildLayoutImmediate(lineObj.GetComponent<RectTransform>());
	}
}

// Line.cs
using System;
using UnityEngine;

[Serializable]
public class Line : IComparable {
    public Texture icon;
    public String text;
    public int priority;

    public Line(String text, int priority = 0) : this(null, text, priority) {
    }

    public Line(Texture icon, String text, int priority = 0) {
        this.text = text;
        this.icon = icon;
        this.priority = priority;
    }

    public int CompareTo(object obj) {
        Line other = (Line)obj;
        return other.priority - priority;
    }
}

Previous snippet | Next snippet