- Home /
StartCoroutine NullReferenceException: Object reference not set to an instance of an object
No doubt this has been answered somewhere else that I couldn't find but I am very new to this and the youtube video I watched didn't have this error. The error is
NullReferenceException: Object reference not set to an instance of an object
This is the line it says is bad:
StartCoroutine(cameraShake.Shake(0.15f, 0.4f));
This is at the top of the page defining cameraShake:
public CameraShake cameraShake;
This is the code for the coroutine: public class CameraShake : MonoBehaviour {
public IEnumerator Shake (float duration, float magnitude)
{
Debug.Log("In IEnumerator");
Vector3 originalPos = transform.localPosition;
float elapsed = 0f;
while (elapsed < duration)
{
float x = Random.Range(-1f, 1f) * magnitude;
float y = Random.Range(-1f, 1f) * magnitude;
Debug.Log("x: " + x);
Debug.Log("y: " + y);
transform.localPosition = new Vector3(x, y, originalPos.z);
elapsed += Time.deltaTime;
yield return null;
}
transform.localPosition = originalPos;
}
}
As I said, I have no clue, thanks for taking the time to read this, even if you didn't help.
Answer by andrew-lukasik · Apr 05, 2020 at 11:18 AM
#if DEBUG
if( cameraShake==null ) Debug.LogWarning($"You forgot to assign '{nameof(cameraShake)}' field in the inspector",gameObject);
#endif
StartCoroutine(cameraShake.Shake(0.15f, 0.4f));
Your answer
Follow this Question
Related Questions
Coroutine Errors 0 Answers
Coroutine Scale goes past maxSize, but still keeps scaling. 2 Answers
StartCoroutine not working in Update!!! 0 Answers
Why does this co-routine not function properly after re-entering the scene? 0 Answers
Problems with C# Coroutines 4 Answers