- Home /
Need an in-depth explanation on this code.
Transform bullet = Instantiate(bulletPrefab) as Transform;
What does this code do?
I know that Instantiate(something) means that you create something in the scene but what I don't understand is that, if instantiate is a function that does something, what is up with "Transform bullet =" ?
You need to go read a book on C# basics; you are not ready for Unity work yet.
Answer by 1337GameDev · Jun 16, 2012 at 03:51 PM
You are assigning a variable (bullet) of type Transform to the Transform of the bullet prefab object you instantiate. It grabs its Transform component of the prefab instance and assigns it to the variable so it can be modified or read.
Answer by aldonaletto · Jun 16, 2012 at 03:52 PM
Instantiate clones the object and returns a reference to it - in this code, the reference has the Transform type and is stored in the bullet variable. Usually this is done to make additional changes to the newly created object - probably set its position and rotation, set its rigidbody.velocity, set a self-destruction time with Destroy(bullet.gameObject) etc.
This is the short Instantiate version - there's another version that takes also position and rotation as arguments. The short version is more used to clone scene objects (the object position and rotation are also cloned), while the latter is more suitable for prefabs (where you must set position and rotation anyway).