Simpler instantiation of enemy

I thought I share my code for instantiating the enemy space ship.

In the lesson, we used this code:

GameObject enemy = Instantiate(enemyPrefab, new Vector3(0,0,0), Quaternion.identity) as GameObject;
enemy.transform.parent = this.transform;

…which was a bit confusing for me, so I checked the doc. There, I found that the Intantiate function has different syntax possibilities. Including one, that fully matches our goal:

public static Object Instantiate(Object original, Transform parent);

My code looks like this:
Instantiate(enemyPrefab, this.transform);

I think it does the same as the twoliner above, doesn’t it?

6 Likes

Yes, it works the same, you can even ditch the this keyword btw.

Tried this and it crashed everything so hard i had to reboot my pc.

1 Like

You can do this too:

Instantiate(enemyPrefab, new Vector3(0,0,0), Quaternion.identity, transform);

So you can instantiate the enemy anywhere with any rotation and parented to the main object.

I just wanted to note here that I tried your way and I found it out Instantiate only began to accept 4 arguments starting with Unity version 5.4. I was banging my head against this issue and thought I’d save others the headache.