Using TextMeshPro - Text in world space
Hi, I'm creating my first 2D topdown shooter game. The player is able to pick up weapons from the ground by standing on one and pressing E. I want a floating animated text "PICK UP [E]" to appear on the interested weapon while the player is on it.
For the text, I created a TextMeshPro - Text prefab with an animation component. I just need to place it in world space on top of the object.
protected override void UpdateInteraction()
{
if (interactions.Count > 0)
{
if (infoText != null) Destroy(infoText.gameObject);
var obj = interactions.Last.Value;
infoText = Instantiate(GameManager.instance.infoTextPrefab); // Instanzia testo informazione
infoText.text.text = obj.interactionPrompt; // Imposta il testo
infoText.GetComponent<RectTransform>().position = obj.transform.position + new Vector3(0, 0.2f, 0); // Posiziona il testo sopra l'oggetto
infoText.SetFollow(obj.transform); // Fai in modo che il testo segua l'oggetto
}
else
{
if (infoText != null) Destroy(infoText.gameObject);
}
}
The SetFollow
function is for making sure the text follows the interested object like it if was its parent, but without rotating. Here's the definition:
using UnityEngine;
using TMPro;
public class InfoText : MonoBehaviour
{
public TextMeshPro text;
Transform follow;
Vector3 positionDelta = Vector3.zero;
private bool hasFollow = false;
public void SetFollow(Transform obj)
{
follow = obj;
positionDelta = transform.position - obj.position;
hasFollow = true;
}
void Update()
{
if (follow != null)
{
transform.position = follow.position + positionDelta;
}
else if (hasFollow && follow == null)
{
Destroy(gameObject);
}
}
}
For some reason, the text object is created far above in the scene, and I cannot move it in the editor in any way.
I think it as something to do with the text needing a world space canvas or something like that. Anybody knowing a solution?
Your answer
