Search code examples
unity-game-engineinstantiationgame-development

Unity Instantiate command not working properly


Whenever I try to Instantiate a particle system in Unity 3D the command positions the particles but doesn't play/runs the animation.

HEre's my code

GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, sleep_);

Unity version-2021.1.1f1


Solution

  • Positions the particles, but doesn't play/run the animation

    If the particle system is instantiated by your code successful, which it seems to do. There are multiple ways to ensure it start when it's created.


    Play on Awake:

    Then you need to ensure that the particle system has Play On Awake set to enabled. As this will ensure the particle system starts playing as soon as you create it in your scene.

    Particle System Main module


    ParticleSystem.Play Altnertive:

    Alternatively you can use the ParticleSystem.Play function to start the particle system in code after you've created it.

    ParticleSystem impactPS = Instantiate(impactEffect, hit.point, 
        Quaternion.LookRotation(hit.normal)) as ParticleSystem;
    impactPS.Play();
    Destroy(impactPS.gameObjkect, sleep_);
    

    Getting Duration of Particle System:

    Additionally if you want to get the duration of your particle system you can use .main.duration. To ensure you don't destroy your gameObject before the particle system has finished playing.

    float sleep_ = impactPS.main.duration;