Hi fellow Devs,
Since I am new to Unity and game scripting this might be a simple fix (hoping it will be). I’ve spent the last 2 days trying different suggested solutions and I come up short somehow.
So here we go.
I have a sound that I want to play when I press a button in this case the “a” button, but I can’t get the sound to play for the life of me. I have attached an audiosource to the object (letterbox A).
With my understanding I should then be able to use the Play function to play the audio.
So what I have done is the following:
function Update ()
{
if (Input.GetKeyDown("a"))
{
var audio : AudioSource = GetComponent.<AudioSource>();
audio.Play();
Destroy(gameObject);
}
}
So what currently happens is, the script compiles successfully and I can run the game in the game window. Once I press the A button the object is removed from the game, but there are no sounds triggered. However if I select the “Play on Awake” setting in the AudioSource that is attached to the object and I start the game, the sound plays.
So I then moved on to make some adjustments by adding the following to the top of the code as I have seen in the unity manual:
#pragma strict
@RequireComponent(AudioSource)
However when I save the script I get the following error:
BCE0153: ‘UnityEngine.RequireComponent’ can be applied on one of these targets only : Class.
I tried to find it on Google, but my GoogleFu is obviously lackluster and I can’t seem to find the problem or if these pieces of code is cardinal to the audioSource.Play.
So I commented that out again.
The last thing that I tried to do tonight is as follows in the code:
var audio : AudioSource;
function Start()
{
audio = GetComponent.<AudioSource>();
}
function Update () {
if (Input.GetKeyDown("a"))
{
audio.Play();
Destroy(gameObject);
}
}
When I save the script with those changes I encounter the following error:
BCE0004: Ambiguous reference ‘audio’: PickupA.audio, UnityEngine.Component.audio.
So I am at a wits end. If anyone of you out there can lend me a helping hand I would appreciate it immensely!