- Home /
How to fade individual gameobjects
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:
public class CombatTextManager : MonoBehaviour
{
public GameObject CombatTextPrefab;
public Transform CombatDisplayparent;
public float speed;
public Vector2 direction;
public float fadeTime;
public bool messageflag;
private static CombatTextManager instance;
public static CombatTextManager Instance
{
get
{
if (instance == null)
{
instance = GameObject.FindObjectOfType<CombatTextManager> ();
}
return instance;
}
}
public void CreateText(string message, Color color)
{
Debug.Log("Message is: " + message);
Debug.Log("Show text and fade");
GameObject ct = Instantiate (CombatTextPrefab);
ct.transform.SetParent (CombatDisplayparent);
ct.GetComponent<CombatText> ().InitializeFade (speed, direction, fadeTime);
ct.GetComponent<Text> ().text = message;
ct.GetComponent<Text> ().color = color;
return;
}
}
Second Script:
public class CombatText : MonoBehaviour
{
private float speed;
private Vector2 direction;
private float fadeTime;
void Update ()
{
float translation = speed * Time.deltaTime;
transform.Translate (direction * translation);
}
public void InitializeFade(float speed, Vector2 direction, float fadeTime)
{
this.speed = speed;
this.direction = direction;
this.fadeTime = fadeTime;
StartCoroutine ("FadeOut");
}
private IEnumerator FadeOut()
{
Debug.Log ("Fading Out...!");
float startAlpha=GetComponent<Text>().color.a;
float rate = 1.0f/fadeTime;
float progress = 0.0f;
while(progress<1.0f)
{
Color tmpColor = GetComponent<Text> ().color;
GetComponent<Text> ().color = new Color (tmpColor.r, tmpColor.b, tmpColor.g, Mathf.Lerp(startAlpha,0,progress));
progress += rate * Time.deltaTime;
yield return null;
}
Destroy (gameObject);
}
}
In case you need to see the call as well...
CombatTextManager.Instance.CreateText ("You Hit the" + EnemyNameText + "For " + damage, Color.black);
What do you mean with "ALL game objects and not the individual gameobjects"? Code looks okayish, although you should really cache your GetComponent calls for better performance.
I mean every gameobject fades out. I'd rather address them individually.
Do you mean that you want them to fade out one at a time? From your code it looks like they fade out as soon as they are created, so if you create them with time in-between each instantiate you will get the effect you want.
Answer by Batzuga · Feb 07, 2020 at 07:56 PM
If you have a custom material for the text, enable gpu instancing from the material settings. I think it changes all the instances of the text material otherwise
All the prefab has on it: rect transform, text, combat text script, layout element, and outline
Oh yeah, I was thinking that you were using a 3D textmesh ins$$anonymous$$d of the canvas text for some reason.