【Unity】AudioSourceでエラー

ゲーム内で音を出したかった

以下のエラーが表示された。

MissingComponentException: There is no ‘AudioSource’ attached to the “×××” game object, but a script is trying to access it.
You probably need to add a AudioSource to the game object “×××”. Or your script needs to check if the component is attached before using it.

AudioSourceをアタッチしてないとダメ見たい。

こんなコードを書いていた。

1
2
3
4
5
6
7
8
9
public AudioClip audioclip;
private AudioSource audiosource;
 
public void OnPointerClick(PointerEventData eventData)
{
    audiosource = gameObject.GetComponent<AudioSource> ();
    audiosource.clip = audioclip;
    audiosource.Play ();
}

まあ、GetComponentで呼んでるからフツーにダメか。
AudioSourceをアタッチしたら音が出るようになりました。

いちいちAudioSourceアタッチするのは面倒なので共通化したい