- Home /
Unity 2D Combat Text Issue With Multiple Enemies
Hi guys, I'm having trouble with my script for damage numbers. When I spawn multiple enemies, the first enemy I hit shows the damage number, but when I then hit a second enemy, it shows the number on the first enemy. (See image for clarification). I think its because it uses the same canvas. All enemies have a seperate canvas for the health and damage numbers. Thanks alot for anyone who helps me out!!
These scripts generate the numbers:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CombatTextControllerEnemy : MonoBehaviour
{
private static CombatText _popupText;
private static GameObject _canvas;
public static void Initialize()
{
_canvas = GameObject.Find("EnemyCanvas");
if (!_popupText)
_popupText = Resources.Load<CombatText>("Prefabs/PopupTextParentEnemy");
}
public static void CreateFloatingTextEnemy(string text, Transform location)
{
CombatText instance = Instantiate(_popupText);
instance.transform.SetParent(_canvas.transform, false);
instance.SetText(text);
}
}
And the script that does the animation and referencing:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class CombatTextEnemy : MonoBehaviour {
public Animator anim;
private TextMeshProUGUI damageText;
private void Start()
{
AnimatorClipInfo[] clipInfo = anim.GetCurrentAnimatorClipInfo(0);
Destroy(gameObject, clipInfo[0].clip.length);
damageText = anim.GetComponent<TextMeshProUGUI>();
}
public void SetText (string text)
{
anim.GetComponent<TextMeshProUGUI>().text = text;
}
}
Answer by bombjack73 · May 08, 2018 at 02:28 PM
I looks like you don't change the position of the text depending on the enemy. That's probably the issue
How do I fix this? because all enemies have a canvas, and I want that each enemy casts its damage text to its own canvas, but now it doesnt yet..
Answer by alexbecker1299 · May 08, 2018 at 02:30 PM
You don't have to use multiple canvas and if your CombatTextControllerEnemy is attached to each enemy, you should not declare objects as a static.
The CombatTextControllerEnemy is not attached to any enemy it gets instantiated in the EnemyHealth script with: CombatTextControllerEnemy.Initialize();
and then when it gets damaged:if (health.CurrentVal != health.$$anonymous$$axVal) { myCanvas.gameObject.SetActive(true); CombatTextControllerEnemy.CreateFloatingTextEnemy(PlayerDamage.ToString(), transform); }