when defeating enemies, I want to adjust the lighting intensity. I want the lighting to adjust over time and not snap from one value to another, so I’m using a coroutine.
for some reason, the line starting the coroutine return a MissingReferenceException for an instance of the class that contains the coroutine.
this is the code:
void onPollutionDwindled(float i_FogDwindled)
{
float fog = Mathf.Clamp(i_FogDwindled, 0.1f, 0.8f);
currentIntensity = fog;
float delta = currentIntensity - light.intensity;
StartCoroutine(updateLight());
IEnumerator updateLight()
{
int numberOfSteps = 3;
float step = delta / numberOfSteps;
for(int i = 0; i < numberOfSteps; i++)
{
light.intensity += step;
light.intensity = Mathf.Clamp(light.intensity, 0.1f, 0.7f);
yield return null;
}
}
}
This is the error message:
MissingReferenceException: The object of type 'LightingManager' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
LightingManager is the class the contains OnFogDwindled
normally I would say that I had just forgotten to instantiate said instance, but the weird thing is that if I change this:
StartCoroutine(updateLight());
To this:
updateLight();
(and of course adjust the function return type to void and comment out the the yield statement), everything works fine, except the fact that the light does not change gradually, which is to be excpeted.
why would a coroutine cause this behaviour?
P.S: If it matters, OnFogDwindled listens to an event in a different class and invoked when an enemy is defeated.
Thanks for the reply! The only listener currently listening to this event is that the
– GameBrewsOnFogDwindled()function. I don't think its' surrounding object is ever null because it is a permanent component on my game manager object. very strange behavior. As mentioned in a post, I tend to dismiss the possibility that its the events fault because when changeUpdateLight()to avoidfunction instead of anIEnumerator"fixes" the problem but that's not the result i'm after.@GameBrews ok! Hm, How is your script added to the game? Is it attached to a gameobject or just floating around by instantiating it as
– KonaLightingManager lm = new LightingManager();From another script? This could Also cause this kind of problem if im not mistaken as IEnumerators depend on MonoBehaviour functionalities that might fail if not set up as intended:)