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
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:
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.