8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unity ParticleSystemで作った打ち上げ花火に音を付ける

Last updated at Posted at 2016-12-07

Unity ParticleSystemで打ち上げ花火(Unity5.5対応)で作った花火に音をつけたかったのですが、SubEmitterで機能するのはParticleSystemだけなのでParticleSystemだけでは完結できませんでした。

・まずベース(ひゅるるるの部分)についていたLoopを外します(つまり打ち上げ花火一つ毎にInstantiateする必要があります)。
2016-12-07_121041.png

・鳴らしたいAudioSourceのついたGameObjectを追加します。
2016-12-07_121131.png

・下記のソースコードを追加し、上記GameObjectをアタッチます。
2016-12-07_121250.png

[修正]dozeou_monさんにいただいたアドバイスを元にコルーチン化しました

FireworksSeed.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FireworksSeed : MonoBehaviour {
    [SerializeField]
    private GameObject explodeAudioObj;
    private ParticleSystem seedPs;

    // Use this for initialization
    void Start () {
        seedPs = GetComponent<ParticleSystem>();
        StartCoroutine(ProgressCo());
    }

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

    private int getSubEmitterParticleNum()
    {
        int ptNum = 0;
        ParticleSystem[] psArr = GetComponentsInChildren<ParticleSystem>();
        foreach (ParticleSystem ps in psArr)
        {
            ptNum += ps.particleCount;
        }
        return ptNum;
    }

    IEnumerator ProgressCo()
    {
        // ひゅるるる待ち
        while (seedPs.particleCount == 0)
        {
            yield return null;
        }
        // ひゅるるるの間は音の位置を移動
        while (seedPs.particleCount > 0)
        {
            ParticleSystem.Particle[] pps = new ParticleSystem.Particle[seedPs.particleCount];
            explodeAudioObj.transform.localPosition = pps[0].position;
            yield return null;
        }
        // 爆発待ち
        while (getSubEmitterParticleNum() == 0)
        {
            yield return null;
        }
        // 爆発音
        explodeAudioObj.GetComponent<AudioSource>().pitch *= Random.Range(0.8f, 1.2f);
        explodeAudioObj.GetComponent<AudioSource>().Play();
        // 消滅待ち
        while (getSubEmitterParticleNum() > 0)
        {
            yield return null;
        }
        // 消滅
        Destroy(gameObject);
    }
}

2016-12-07_125250.png

8
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?