- Home /
Question by
rsud · Jun 18, 2013 at 04:47 PM ·
c#audiosourceusage
How to use audiosource in c# in Unity 4? Did it change?
In a Unity 3 test game I did the following to play a sound....
AudioSource gmMus;
public AudioClip music;
void Start()
{
gmMus = (AudioSource) GetComponent(typeof(AudioSource));
}
void Update()
{
gmMus.PlayOneShot (music);
}
The above worked fine in Unity 3.
In Unity 4 the same code does not work.
The ' gmMus = (AudioSource) GetComponent(typeof(AudioSource));' fails and NULL is assigned to gmMus.
Why this change?
In the Unity 4 documentation I now see the following:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class example : MonoBehaviour {
public AudioClip impact;
void OnCollisionEnter()
{
audio.PlayOneShot(impact, 0.7F);
}
}
This new sample code confuses me. How did the var 'audio' get assigned for 'audio.PlayOneShot(impact, 0.7F);' to work?
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613104418im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
AudioClip stuttering while loop is OFF and not using function Update? 1 Answer
Change AudioSource output via Script 1 Answer
Audio Manager or not? Audio System 0 Answers