So, I was doing something a little more complex, but it wasn’t working due to the coroutine, then I decided I wanted to get some more experience with it, so I made/used the very simple fade coroutine. However, I ended up with the surprise that that didn’t work either.
using UnityEngine;
using System.Collections;
public class fade : MonoBehaviour {
IEnumerator Fade() {
for (float f = 1f; f >= 0; f -= 0.1f) {
Color c = this.GetComponent<Renderer>().material.color;
c.a = f;
this.GetComponent<Renderer>().material.color = c;
yield return null;
}
}
void Update() {
if (Input.GetKeyDown("f")) {
StartCoroutine("Fade");
}
As you can probably observe, that’s the example coroutine from the Unity documentation, but it doesn’t work.
So, then I decided to make a coroutine that affects the position of a gameObject, and it did actually work. It gives the effect of movement with negative acceleration, but with an initial speed != 0, until the gameObject stops.
IEnumerator Move() {
for (float f = 5f; f>=0; f-=1f) {
Vector3 newPos = this.gameObject.transform.position;
newPos.x += f;
this.gameObject.transform.position = newPos;
yield return null;
}
void Update() {
if (Input.GetKeyDown ("m")) StartCoroutine("Move");
}
So…what’s wrong with the fading coroutine? For a little more debugging and for future uses, I ended up changing it a little to:
void setColor(Color c)
{
this.GetComponent<Renderer> ().material.color = c;
Debug.Log ("Changed color to : " + c);
}
IEnumerator Fade() {
for (float f = 1f; f >= 0; f -= 0.1f) {
Color c = this.GetComponent<Renderer>().material.color;
c.a = f;
setColor (c);
yield return null;
}
}
void Update() {
if (Input.GetKeyDown("f")) StartCoroutine("Fade");
}
The setColor() function does work, I tested it , and in the console, the message(s) do/does appear correctly, but the object itself is still 100% opaque.
Console log :
Changed color to : RGBA(1.000, 0.000, 0.000, 1.000)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.900)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.800)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.700)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.600)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.500)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.400)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.300)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.200)
Changed color to : RGBA(1.000, 0.000, 0.000, 0.100)
What’s wrong?
If it’s a typo or a really small mistake that I somehow couldn’t notice after almost an hour of debugging…oh well, it’s happened before :l .