::That is a nice spot. Here is how you fix it (changes highlighted in green below):
IEnumerator GenerateFloatingTextCoroutine(string text, Transform target, float duration = 1f, float speed = 50f)
{
// Start generating the floating text.
GameObject textObj = new GameObject("Damage Floating Text");
RectTransform rect = textObj.AddComponent();
TextMeshProUGUI tmPro = textObj.AddComponent();
tmPro.text = text;
tmPro.horizontalAlignment = HorizontalAlignmentOptions.Center;
tmPro.verticalAlignment = VerticalAlignmentOptions.Middle;
tmPro.fontSize = textFontSize;
if (textFont) tmPro.font = textFont;
rect.position = referenceCamera.WorldToScreenPoint(target.position);
// Makes sure this is destroyed after the duration finishes.
Destroy(textObj, duration);
// Parent the generated text object to the canvas.
textObj.transform.SetParent(instance.damageTextCanvas.transform);
// Pan the text upwards and fade it away over time.
WaitForEndOfFrame w = new WaitForEndOfFrame();
float t = 0;
float yOffset = 0;
while(t < duration)
{
// Fade the text to the right alpha value.
tmPro.color = new Color(tmPro.color.r, tmPro.color.g, tmPro.color.b, 1 - t / duration);
// Pan the text upwards.
if(target)
{
yOffset += speed * Time.deltaTime;
rect.position = referenceCamera.WorldToScreenPoint(target.position + new Vector3(0,yOffset));
}
else
{
rect.position += Vector2.up * speed * Time.deltaTime;
}
// Wait for a frame and update the time.
yield return w;
t += Time.deltaTime;
// Fade the text to the right alpha value.
tmPro.color = new Color(tmPro.color.r, tmPro.color.g, tmPro.color.b, 1 - t / duration);
}
}
Basically, you check if the target exists. If it exists, you calculate it based on the target’s position. Otherwise, you just offset it upwards based on its current position.
Let me know if this works!
I’ve also added a Bug Reporter badge to your profile, as thanks for spotting this issue.