So i’m trying to make text fade in once the player collides with the object. This is my code but for some reason, my text isn’t appearing even though it says in the debug log that the alpha is getting increased.
Please tell me if there is anymore information that I need to provide. I would gladly do anything to get a good answer.
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class PersonaScript : MonoBehaviour {
public string messageText;
public float Delay;
public Text Ptext;
public GameObject Message;
private Color MatColor;
void Start () {
Ptext.text = messageText;
MatColor = Ptext.color;
MatColor.a = 0;
}
void OnTriggerEnter (Collider other) {
if (other.CompareTag ("Player")){
StartCoroutine("FadeIn");
}
}
IEnumerator FadeIn(){
while(MatColor.a <= 1){
Debug.Log(MatColor.a);
MatColor.a += .3f;
yield return new WaitForSeconds(.2f);
}
yield return new WaitForSeconds(Delay);
}
}
You must assign the colour back to the text’s colour.
Color is a struct (therefore, copied on assignment - not referenced). You are updating ‘MatColor’ 's alpha property, but the text color doesn’t know that you’ve done that… until you assign it back
Glad you got it working. FYI, though, you really don’t need to work this hard to fade in text. You can just call CrossFadeAlpha on it, and magic happens.
Thanks for the advice but may I ask how I should use it? I read the documentation and tried changing my script. It doesn’t work. I’d really like to simplify my code.
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class PersonaScript : MonoBehaviour {
public string messageText;
public float Delay;
public Text Ptext;
public GameObject Message;
private Color MatColor;
void Awake () {
Ptext.text = messageText;
MatColor = Ptext.color;
MatColor.a = 0;
Ptext.color = MatColor;
}
void Update(){
}
void OnTriggerEnter (Collider other) {
if (other.CompareTag ("Player")){
Ptext.CrossFadeAlpha(1, 1.5f, false);
// StartCoroutine("FadeIn");
}
}
IEnumerator FadeIn(){
while(MatColor.a <= 1){
Debug.Log(MatColor.a);
MatColor.a += .2f;
Ptext.color = MatColor;
yield return new WaitForSeconds(.5f);
}
yield return new WaitForSeconds(Delay);
}
}
This is a common point of confusion — Graphic.CrossFadeAlpha does not operate on the color of the Graphic (the Image component in this case), like you might expect. Instead it operates on the alpha of the CanvasRenderer component, which is easy to overlook since it’s not a very accessible property. (It’s exposed only via the GetAlpha and SetAlpha methods, and not visible in the Inspector.)
But anyway, here’s how to fix your script:
Change the color of your Text object back to a nice solid (opaque) color.
In the Start method of your script, add code like this:
// make Ptext initially invisible
Ptext.GetComponent<CanvasRenderer>().SetAlpha(0);
That’s it. Then of course you can delete most of the rest of your script — all you need is the CrossFadeAlpha call to make it fade back in.