Search code examples
c#unity-game-enginecollision-detectionparticlesparticle-system

How to transform position from one object to the current player position?


So i have this little particlesystem attached on my player so if he dies he explodes. But i cant simply attach the particlesystem under the player because if i destroy my player the childs of the gameobjects get destroyed as well. The animation runs if he dies but not on his current spot so some ideas for that? Maybe to transform the position to the current position of the player while he dies? Here my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerdeath : MonoBehaviour
{

    public ParticleSystem death_explosion;

    // Start is called before the first frame update
    void Start()
    {

        death_explosion.Stop();
    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "deathcube")
            Destroy(gameObject);
        Debug.Log("collision detected");
        death_explosion.Play();
    }
}

Solution

  • What you could do is create a prefab of the particle object and reference it inside your script like so:

    public ParticleSystem death_explosion_Prefab;
    

    And instead of attaching it to the Player as a child, instantiate it on collision:

    void OnTriggerEnter(Collider other)
        {
            if (other.gameObject.tag == "deathcube")
            {
                Debug.Log("collision detected");
                Instantiate(death_explosion_Prefab, gameObject.transform.position, Quaternion.identity);
                Destroy(gameObject);
            }
        }