How to fade individual gameobjects

Updated on February 10, 2020 in Unity
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on February 10, 2020

This script will fadeout the gameobjects that are instantiated, except that it fades out and destroys ALL game objects not the individual gameobjects as expected. Do I need to name each one when they are instantiated?

First Script:

  1. public class CombatTextManager : MonoBehaviour
  2. {
  3. public GameObject CombatTextPrefab;
  4. public Transform CombatDisplayparent;
  5. public float speed;
  6. public Vector2 direction;
  7. public float fadeTime;
  8. public bool messageflag;
  9. private static CombatTextManager instance;
  10. public static CombatTextManager Instance
  11. {
  12. get
  13. {
  14. if (instance == null)
  15. {
  16. instance = GameObject.FindObjectOfType<CombatTextManager> ();
  17. }
  18. return instance;
  19. }
  20. }
  21. public void CreateText(string message, Color color)
  22. {
  23. Debug.Log("Message is: " + message);
  24. Debug.Log("Show text and fade");
  25. GameObject ct = Instantiate (CombatTextPrefab);
  26. ct.transform.SetParent (CombatDisplayparent);
  27. ct.GetComponent<CombatText> ().InitializeFade (speed, direction, fadeTime);
  28. ct.GetComponent<Text> ().text = message;
  29. ct.GetComponent<Text> ().color = color;
  30. return;
  31. }
  32. }

Second Script:

  1. public class CombatText : MonoBehaviour
  2. {
  3. private float speed;
  4. private Vector2 direction;
  5. private float fadeTime;
  6. void Update ()
  7. {
  8. float translation = speed * Time.deltaTime;
  9. transform.Translate (direction * translation);
  10. }
  11. public void InitializeFade(float speed, Vector2 direction, float fadeTime)
  12. {
  13. this.speed = speed;
  14. this.direction = direction;
  15. this.fadeTime = fadeTime;
  16. StartCoroutine ("FadeOut");
  17. }
  18. private IEnumerator FadeOut()
  19. {
  20. Debug.Log ("Fading Out...!");
  21. float startAlpha=GetComponent<Text>().color.a;
  22. float rate = 1.0f/fadeTime;
  23. float progress = 0.0f;
  24. while(progress<1.0f)
  25. {
  26. Color tmpColor = GetComponent<Text> ().color;
  27. GetComponent<Text> ().color = new Color (tmpColor.r, tmpColor.b, tmpColor.g, Mathf.Lerp(startAlpha,0,progress));
  28. progress += rate * Time.deltaTime;
  29. yield return null;
  30. }
  31. Destroy (gameObject);
  32. }
  33. }

In case you need to see the call as well…

  1. CombatTextManager.Instance.CreateText ("You Hit the" + EnemyNameText + "For " + damage, Color.black);
  • Liked by
Reply
0 on February 10, 2020
  1. Are you setting the prefab to an object in the scene? or from the prefab folder?
  2. try StartCoroutine(FadeOut()); instead of “FadeOut”
  3. Maybe try moving the StartCoroutine to Start, instead of in it’s initialize
  • Liked by
Reply
Cancel