NullReferenceException: Object reference not set to an instance of an object

Hey, I’m instantiating an Object with a yield, but it give the error:
“NullReferenceException: Object reference not set to an instance of an object”

I don’t know where is the problem, because I ever used that and ever works.

It’s a simple code

using UnityEngine;
using System.Collections;

public class CanhaoLevel1 : MonoBehaviour 
{
	public Rigidbody balaCanhao;
	
	void Start () 
	{
		StartCoroutine(Atirar ());
	}
	
	IEnumerator Atirar()
	{
		    yield return new WaitForSeconds(1);
		    Rigidbody clone;
            clone = Instantiate(balaCanhao, transform.position, transform.rotation) as Rigidbody;
            clone.velocity = transform.TransformDirection(Vector3.up * 10);		
			StartCoroutine(Atirar ());
	}
}

Someone has some Idea ?

Complete error:

NullReferenceException: Object reference not set to an instance of an object
CanhaoLevel1+c__Iterator2.MoveNext () (at Assets/CanhaoLevel1.cs:19)

If you’re wanting to loop your Coroutine, use a while statement instead of calling the Coroutine inside of itself. Also be sure to check if your object is null or not before you instantiate it. Try this:

using UnityEngine;
using System.Collections;

public class CanhaoLevel1 : MonoBehaviour
{
	public Rigidbody balaCanhao;
	
	void Start()
	{
		StartCoroutine(Atirar());	
	}

	IEnumerator Atirar()
	{
		while(true && balaCanhao != null)
		{
			yield return new WaitForSeconds(1);
			Rigidbody clone = Instantiate(balaCanhao, transform.position, transform.rotation) as Rigidbody;
			clone.velocity = transform.up * 10;
			yield return new WaitForEndOfFrame();
		}
	}
}

Eae manolo brasileiro Fred :slight_smile:

It seems you are trying to invoke the method Atirar() inside the IEnumerator that you creating.

You really can call that method inside the method you created?

Like:

void Start(){
Start()
}