Why do we code the Instantiate differently for the particle Prefab?

   private void Fire()
    {
        GameObject laser = Instantiate(
                     laserPrefab,
                     transform.position,
                     Quaternion.identity) as GameObject;
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -projectileSpeed);        
    }

I’m still new at coding so this might be a silly question, but why is it that when we instantiated the laserPrefab we determinde “as GameObject” at the end and we don’t have to do it when we instatiate the particle explosion? Same question with the transform Quaternion.identity.

Destroy(gameObject);
        GameObject particleExplosion = Instantiate(deathVFX, transform.position, transform.rotation);

Hi rohadgal,

In past versions of Unity, the Instantiate method returned an object of type Object. (Yes, there is a class in C# named Object.) To be able to assign the returned object to a variable of type GameObject, we had to cast the returned object with as GameObject.

In newer versions of Unity, that’s not necessary anymore. However, game developers who have been using Unity for a couple of years still cast out of habit.

Did this clear it up for you? :slight_smile:


See also:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms