Putting instantiate inside a variable

Hello everyone :slight_smile:

I was just wondering today when i was working with unity, why use a variable when instantiating something? what is the benefit of:

var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);

from just doing

Instantiate(thePrefab,transform.position,transform.rotation);

Because you might need to access your newly-created instance immediately after, e.g. to set some property:

var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
instance.renderer.enabled = false;

You must assign the result of Instantiate to a variable when you want to do something else with the newly created object - child it to another object, apply a force to it, etc. If youโ€™re creating a rocket, for instance, you must accelerate the object towards the target - the code would be something like this:

 var bullet: GameObject = Instantiate(bulletPrefab, ...);
 bullet.rigidbody.AddForce(bullet.transform.forward * shootingForce);