NullReferenceException with Instantiate()

I get a NullReferenceException on a object cloned with Instantiate() on line 2 and 3. Why is it that line 1 will give a valid output but line 2 and 3 will give a null result when what has been changed is only assigning the object instantiated in line 1 to a variable (projectile) ? The laser clone object did appear in the scene.

Appreciate any help on this… thanks!

GameObject projectile = Instantiate(laserPrefab, transform.position, Quaternion.identity) as GameObject;
        print(Instantiate(laserPrefab, transform.position, Quaternion.identity)); // 1
        print(projectile); // 2
        projectile.GetComponent<Rigidbody2D>().velocity = Vector2.up * 2.0f * Time.deltaTime; // 3 <--NullReferenceException on this line

Console Output

laserPrefab(Clone) (Laser)
UnityEngine.MonoBehaviour: print(Object)
Player:Fire() (at Assets/Scripts/Player.cs:86)

Null
UnityEngine.MonoBehaviour: print(Object)
Player:Fire() (at Assets/Scripts/Player.cs:87)

NullReferenceException: Object reference not set to an instance of an object
Player.Fire () (at Assets/Scripts/Player.cs:88)

it would appear it’s not able to cast the return to a gameobject…? what is “laserPrefab”?

So it looks like laserPrefab is declared as a Laser:

public Laser laserPrefab;

What happens when you Instantiate a component like a MonoBehaviour is that Unity copies the gameObject the component is attached to, and then returns the copied component.

So your instantiate call is creating a copy of the laserPrefab object (called laserPrefab(Clone)), and returning the Laser script attached to it.

You are then casting that laser script to GameObject. That’s not going to work. The ‘as’ cast silently returns null if it fails.

To get the GameObject, simply cast to the correct type, and get the gameobject:

Laser laserClone =Instantiate(laserPrefab, transform.position, Quaternion.identity) as Laser;
GameObject projectile = laserClone.gameObject;

You can also Instantiate the gameobject directly, that’ll get you the correct clone:

GameObject projectile = Instantiate(laserPrefab.gameObject, transform.position, Quaternion.identity) as GameObject;

Thank you everyone. I made the mistake of thinking I had inserted the laser gameobject as a parameter to Instantiate(), when what I had inserted was only the laser component object.