- Home /
Putting instantiate inside a variable
Hello everyone :)
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);
Answer by tanoshimi · Nov 04, 2013 at 04:15 PM
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;
Answer by aldonaletto · Nov 04, 2013 at 04:30 PM
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);
...and see the docs for the full rocket example: http://docs.unity3d.com/Documentation/$$anonymous$$anual/InstantiatingPrefabs.html about 1/2-way down.