アセットに音楽データを入れる。

空のオブジェクトを作成

(GameObject)

scriptを追加(GameObjectScript)

それにオーディオソースを2つ追加。

曲をオーディオクリップにドラック。

GameObjectScriptのプログラミング

 

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

        if (Input.GetKeyDown(KeyCode.Space)) {

            // 音楽再生
            this.GetComponent<AudioSource>().Play();
        }

        AudioSource[] ad = this.GetComponents<AudioSource>();

        if (Input.GetKeyDown(KeyCode.A)) {
            ad[0].Play();
        }

        if (Input.GetKeyDown(KeyCode.B)) {
            ad[1].Play();
        }

        if (Input.GetKeyDown(KeyCode.C))
        {
            GameObject go = 
                GameObject.Find("GameObject2");

            GameObject2Script sc =
                go.GetComponent<GameObject2Script>();

            sc.PlaySound3();
        }

    }

もうひとつ空のオブジェクトを

GameObject2を追加。

scriptを追加(GameObjectScript2)

それにオーディオソースを残りのひとつを追加。

 

GameObjectScript2のプログラミング

 

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

public class GameObject2Script : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        
    }

    public void PlaySound3() {

        this.GetComponent<AudioSource>().Play();

    }
}