Instantiate vs Instantiate as gameobject
Prototyping a 2d action roguelike(Enter The Gungeon/Nuclear Throne influenced) and I'm trying to figure out the difference between these two lines of code, and a sample use case for both:
Using Instantiate to spawn a bullet prefab
Instantiate (bullet, transform.position, Quaternion.identity);
vs
Instantiating a prefab bullet as a GameObject
GameObject projectile = Instantiate (bullet, transform.position, Quaternion.identity) as GameObject;
I've been searching around, and can find similar topics but none that address this question in this fashion(however that may be because of my search terms). Appreciate any help, thank you.
Answer by tanoshimi · Feb 04, 2017 at 08:28 AM
It's called casting, and it's used to convert an object from one type to another. Note it's not specific to Instantiate at all - it's part of C#.
Instantiate returns an Object. That's not hugely useful. So the second example casts the result as a gameobject and then assigns it to the "projectile" variable so you can do other things with it.
Thank you! This was just the type of explanation that I was looking for.
As for example Adding a component? So the thing there is that without the as GameObject i couldn't treat the spawned element as a unities GameObject?
This is great, thank you.
From what you've said my assumption is to use: - instantiate(GameObject);
if I'm not going to do anything in the script with the instantiated object - instantiate(GameObject) as GameObject;
if I'm going to assign it to a variable and then modify it in the script.