Tooltips with the new Unity UI (uGUI)

Since I needed tooltips to test something really quick I went to see if there was an implementation in the new uGUI system. Unfortunately there were none but a few custom made solutions from other devs. None of those suited me though, so I quickly built my own, very rough version. It consists of two scripts and a view that is the tooltip.

Tooltip Demo

Tooltip Demo

TooltipTrigger

This script is put on all the objects you want to trigger the tooltip. It contains the text that should be shown as a public variable. Everything else is handled by the TooltipView.

using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;

namespace Sharkbomb.View {
	public class TooltipTrigger : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler {

		public string text;

		public void OnPointerEnter(PointerEventData eventData)
		{
			StartHover(new Vector3(eventData.position.x, eventData.position.y - 18f, 0f));
		}	
		public void OnSelect(BaseEventData eventData)
		{
			StartHover(transform.position);
		}
		public void OnPointerExit(PointerEventData eventData)
		{
			StopHover();
		}
		public void OnDeselect(BaseEventData eventData)
		{
			StopHover();
		}

		void StartHover(Vector3 position) {
			TooltipView.Instance.ShowTooltip(text, position);
		}
		void StopHover() {
			TooltipView.Instance.HideTooltip();
		}

	}
}

TooltipView

This script is put on a separate uGUI object that is the actual visible tooltip. It’s a singleton so the many TooltipTriggers can access it quickly and easily.

using UnityEngine;
using System.Collections;

namespace Sharkbomb.View {
	public class TooltipView : MonoBehaviour {
		
		public bool IsActive {
			get {
				return gameObject.activeSelf;
			}
		}
		//public CanvasGroup tooltip;
		public UnityEngine.UI.Text tooltipText;

		void Awake() {
			instance = this;
			HideTooltip();
		}

		public void ShowTooltip(string text, Vector3 pos) {
			if (tooltipText.text != text)
				tooltipText.text = text;

			transform.position = pos;

			gameObject.SetActive(true);
		}
		
		public void HideTooltip() {
			gameObject.SetActive(false);
		}
		
		// Standard Singleton Access 
		private static TooltipView instance;
		public static TooltipView Instance
		{
			get
			{
				if (instance == null)
					instance = GameObject.FindObjectOfType<TooltipView>();
				return instance;
			}
		}
	}
}

As said, it’s a very simple script. There’s a bunch of things it doesn’t do and a few things to be aware of:

– It doesn’t wait a second before showing the tooltip.
– It currently places the tooltip over the object when selecting it via keyboard
– The tooltip can leave the boundaries of the screen and become (partially) invisible
– The tooltip doesn’t move with the cursor – that means it can block raytraces and cause flickering as it blocks the ray to the hovered object, disappearing and reappearing in a new pos


  • Setia Budi

    Great help, Thanks !!