I’m working on an project and I’ve hit a dead end-
I want to get an object with a text mesh inside it to behave a certain way with a box collider, so that when the player enters the collider, the text fades in, and when the player leaves, it fades back out to invisible. I’ve been trying to look for ways to get it to work but nothing seems to be behaving correctly or it creates errors that cannot be fixed.
I would most definitely appreciate the help, as I’ve been scouring for fixes for weeks now with no answers or suitable fixes.
You should be able to just fade out the alpha.
I make a small script, but it doesn’t work the why i thought.
I thought the alpha was a value from 0 to 1, I can only get it working with 0 to 255.
take at look and maybe it will help you fade the text in and out.
My script uses OnTriggerEnter() and OnTriggerExit()
Edit: retested, and found my error, this is working with a speed of 0.02f
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fadeText : MonoBehaviour {
private MeshRenderer text;
public float fadeSpeed; //0.02f worked good for me
void Start () {
text = GetComponent<MeshRenderer>();
}
void OnTriggerEnter(Collider other)
{
StartCoroutine(Fade(true));
}
void OnTriggerExit(Collider other)
{
StartCoroutine(Fade(false));
}
IEnumerator Fade(bool fadeIn)
{
float waitTime = 0.01f;
float a;
if(fadeIn)
{
Debug.Log("fade in");
a = 1;
while (a > 0)
{
yield return new WaitForSeconds(waitTime);
a -= fadeSpeed;
text.material.color = new Color(1, 1, 1, a);
}
}
else
{
Debug.Log("fade out");
a = 0f;
while (a < 1)
{
yield return new WaitForSeconds(waitTime);
a += fadeSpeed;
text.material.color = new Color(1, 1, 1, a);
}
}
}
}
Just adding a thought - if the fade speed was desired as a bit longer and you could possibly enter and exit while it was going, store the coroutine in a variable, so you could stop it before starting the new one.