Help us understand the problem. What is going on with this article?

Unityで音を再生する

More than 5 years have passed since last update.

GameObjectにサウンドファイルをドラック&ドロップして
audio Sourceを作った後で以下のスクリプトを使って音声を再生させる事ができます。
また、AudioClipを複数作る事でサウンドの切り替えも可能です。

using UnityEngine;
using System.Collections;

public class SoundTest : MonoBehaviour {
    public AudioClip audioClip1;
    public AudioClip audioClip2;
    public AudioClip audioClip3;
    private AudioSource audioSource;

    void Start () {
        audioSource = gameObject.GetComponent<AudioSource>();
        audioSource.clip = audioClip1;
        audioSource.Play ();
    }

}

Insectorは以下のようになります。
スクリーンショット 2014-08-20 14.59.28.png

Audio Listenerも追加する。
スクリーンショット 2014-10-03 10.52.08.png

音声を同時に再生させる場合は、以下のように
AudioSourceを2つ以上にして操作するようにすれば良いです。

using UnityEngine;
using System.Collections;

public class PlaySound : MonoBehaviour {
    private AudioSource[] sources;
    void Start () {
        sources = gameObject.GetComponents<AudioSource>();
    }


    void Update () {
        if(Input.GetKeyDown(KeyCode.K)) {
            sources[0].Play();
        }
        if(Input.GetKeyDown(KeyCode.L)) {
            sources[1].Play ();
        }
    }
}

Inspectorは、AudioSourceを複数にしています。
スクリーンショット 2015-04-20 20.27.01.png

再生時に音を鳴らしたくない場合は
Play On Awakeにチェックを入れなければなりません!

amano-kiyoyuki
絶対領域拡張計画「光るスカート」の開発者。 モノづくり楽しすぎ。
http://www.kayac.com/team/amano-kiyoyuki
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした