Null reference at GetComponent<Image>().color = new Color (0, 0, 0, alphaLevel);

Hello, I made a black fade out image on my scene to give it a fade out effect using an
Image Screenshot - 01c7373a6c994c1007cd9ac70323be42 - Gyazo

The code i am using is:

public class IntroStorylineController : MonoBehaviour {

public Text IntroText;
public float alphaLevel = 1f;
public float totalTime = 0;

void Start () {

//StartCoroutine (waitTime ());
}

void Update () {

totalTime += Time.deltaTime;

if (totalTime >= .2) {

alphaLevel -= .01f;
totalTime = 0;

}

GetComponent().color = new Color (0, 0, 0, alphaLevel);

}

IEnumerator waitTime() {

yield return new WaitForSeconds (3f);
Update ();
IntroText.enabled = false;

}
}

The scene fades out correctly but am getting a recurring null reference exception

on GetComponent().color = new Color (0, 0, 0, alphaLevel);

I have the above script attached to the image gameobject.

Any1 knows what might be going wrong please? Thanks

Few things… I don’t think it’s a good idea to call Update() from another function (in your waitTime, for instance).
Because update already runs on its own*.
Next, is that … since update is always running, it’s always setting the alpha value and trying to apply to it the new colour…
I’m not 100% sure about the null reference right now … but if you re-write it a little, I could take a look after.

1 Like

null reference means that it did not find an Image script on the gameobject. so verfy that you one. you might need to change it to renderer
GetComponent().material.color

1 Like