Dear lovely community,
I’am creating a 2d game and I would like to add a floating damage pop up text every time I click on a certain object. For this I clone a prefab with a text popup animation every time I click on the screen. The prefab is put into the game as intended however the animation isn’t working. When I put only one animation into the screen it works. I don’t simply don’t know why it isn’t working… So how can I clone a prefab with an animation and make it working with other animations of the same prefab already running? This is driving me crazy and some help would awesome!
using UnityEngine;
public class Enemy : MonoBehaviour {
public int health;
void Start()
{
FloatingTextController.Initialize();
}
public virtual void TakeDamage(int amount)
{
FloatingTextController.CreateFloatingText(amount.ToString(), transform);
Debug.LogFormat("{0} was dealt {1} damage", gameObject.name, amount);
if ((health -= amount) <= 0)
Die();
}
public virtual void Die()
{
Debug.Log(gameObject.name + " has died.");
}
void OnMouseDown()
{
this.TakeDamage(Random.Range(0, 100));
}
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class FloatingText : MonoBehaviour {
public Animator animator;
private Text damageText;
void OnEnable()
{
AnimatorClipInfo[] clipInfo = animator.GetCurrentAnimatorClipInfo(0);
Debug.Log(clipInfo.Length);
//Destroy(gameObject, clipInfo[0].clip.length);
damageText = animator.GetComponent<Text>();
}
public void SetText(string text)
{
damageText.text = text;
}
}
using UnityEngine;
using System.Collections;
public class FloatingTextController : MonoBehaviour {
private static FloatingText popupText;
private static GameObject canvas;
public static void Initialize()
{
canvas = GameObject.Find("Canvas");
if (!popupText)
popupText = Resources.Load<FloatingText>("Prefabs/PopupTextParent");
}
public static void CreateFloatingText(string text, Transform location)
{
FloatingText instance = Instantiate(popupText);
Vector2 screenPosition = Camera.main.WorldToScreenPoint(new Vector2(location.position.x + Random.Range(-.2f, .2f), location.position.y + Random.Range(-.2f, .2f)));
//Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
instance.transform.SetParent(canvas.transform, false);
instance.transform.position = screenPosition;
instance.SetText(text);
instance.GetComponent<Animator>().Play("PopupText");
}
}