Forum begins after the advertisement:
[Part 14] MissingReferenceException with floating text RectTransform
Home › Forums › Video Game Tutorial Series › Creating a Rogue-like Shoot-em Up in Unity › [Part 14] MissingReferenceException with floating text RectTransform
- This topic has 18 replies, 5 voices, and was last updated 5 months ago by
Terence.
-
AuthorPosts
-
May 28, 2024 at 4:48 am #14789::
For me, there is one remaining issue. When the
target
dies then the text does not reamain where the target died. It rather follows the camera, which I guess is not intended.How would u fix that ?
May 28, 2024 at 2:20 pm #14790::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.
December 7, 2024 at 8:17 pm #16684December 8, 2024 at 1:16 am #16690 -
AuthorPosts
- You must be logged in to reply to this topic.
Advertisement below: