Unity3D Play sound from particle

3.1k views Asked by At

I am trying to play a sound when a particle collides with a wall. Right now, it just plays the sound from the parent object, which is the player.

However, I want the sound to play from the particle. Which means when a particle is far to the left, you vaguely hear the sound coming from the left.

Is there a way to play the sound from a particle, when it collides?

3

There are 3 answers

0
Emilio Martinez On BEST ANSWER

You can use OnParticleCollision and the ParticlePhysicsExtensions, and play a sound with PlayClipAtPoint:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(ParticleSystem))]
public class CollidingParticles : MonoBehaviour {

    public AudioClip collisionSFX;

    ParticleSystem partSystem;
    ParticleCollisionEvent[] collisionEvents;

    void Awake () {

        partSystem = GetComponent<ParticleSystem>();
        collisionEvents = new ParticleCollisionEvent[16];
    }

    void OnParticleCollision (GameObject other) {

        int safeLength = partSystem.GetSafeCollisionEventSize();
        if (collisionEvents.Length < safeLength)
            collisionEvents = new ParticleCollisionEvent[safeLength];

        int totalCollisions = partSystem.GetCollisionEvents(other, collisionEvents);
        for (int i = 0; i < totalCollisions; i++)
            AudioSource.PlayClipAtPoint(collisionSFX, collisionEvents[i].intersection);

        print (totalCollisions);
    }
}

The problem is that the temporary AudioSource created by PlayClipAtPoint cannot be retrieved (to set it as 3D sound). So you are better off creating your own PlayClipAtPoint method that instantiates a prefab, already configured with a 3D AudioSource and the clip you want, and run Destroy(instance, seconds) to mark it for timed destruction.

0
game development germ On

The only way I can imagine is overriding animation of particle system via GetParticles/SetParticles. Thus you can provide your own collision detection for particles with Physics.RaycastAll and play sound when collisions occured.

0
Xeno Gaming On
AudioSource audioSourcee;
public float timerToPlay;
float timerToSave;

void Start()
{
     timerToSave = timerToPlay;
}

void OnEnable()
{
    timerToPlay = timerToSave;
}

// Update is called once per frame
void Update()
{
    if(timerToPlay>0)
        timerToPlay -= Time.deltaTime;
    if(timerToPlay<=0)
        audioSourcee.Play();
}