Search Unity

Resolved instantiating a particle system as a child object

Discussion in 'Scripting' started by glacierqsr, Nov 28, 2022.

  1. glacierqsr

    glacierqsr

    Joined:
    Nov 9, 2021
    Posts:
    11
    So I've got a smoke trail that comes out of the gun when firing it,
    I'm executing this code by simply calling the function when I'm shooting.
    Code (CSharp):
    1.     private void GunGraphics()
    2.     {
    3.         if (muzzleFlash != null)
    4.             Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);
    5.         if (SmokeTrail != null)
    6.             Instantiate(SmokeTrail, attackPoint.position, attackPoint.rotation);
    7.     }
    I'm instantiating the code like this, but the smoke trail is not a child off the attackPoint transform, I've tried to use attackPoint.Setparent and attackPoint.parent.position, though I couldn't figure it out with that.

    Any leads in the right direction would be great, thanks in advance.
     
  2. rickitz5

    rickitz5

    Joined:
    Aug 8, 2021
    Posts:
    31
    So currently, setting attackPoints parent will do nothing, because you are only using attackPoints position in the Instantiate method. Instead do this -
    Code (CSharp):
    1. ParticleSystem smoke = Instantiate(SmokeTrail, attackPoint.position, attackPoint.rotation);
    2. smoke.transform.parent = attackPoint;
    This changes the particle systems instance as child under attackPoint.
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,474
    As above but also look at the docs for Instantiate, you can pass in the parent right there which is slightly quicker.

    Code (CSharp):
    1. var smoke = Instantiate(SmokeTrail, attackPoint.position, attackPoint.rotation, attackPoint);
     
  4. glacierqsr

    glacierqsr

    Joined:
    Nov 9, 2021
    Posts:
    11
    awesome!!! thanks a lot, after trying a few things I ended up with this, which seems to work.
    Code (CSharp):
    1. Instantiate(SmokeTrail, attackPoint.position, attackPoint.rotation, transform.parent);