I don't know how to play sound in Unity3D

Yes, I have never worked with Unity’s sound system, I managed to do this:

public class JustAmbience : MonoBehaviour {
            public AudioClip backgroundMusic;
            void Start() {
                audio.PlayOneShot(backgroundMusic);
            }
        }

But it shouts that it’s deprecated and I should use XYZ instead, so I finished up as:

using UnityEngine;
using System.Collections;

public class JustAmbience : MonoBehaviour {
    public AudioClip backgroundMusic;
    void Start() {
        audio.GetComponent<AudioSource>(backgroundMusic);
    }
}

Still exactly same error, and I don’t know how to make it work. I saved file, no slots, just file included.

Errors:
Assets/JustAmbience.cs(7,17): error CS0619: UnityEngine.Component.audio' is obsolete: Property audio has been deprecated. Use GetComponent() instead. (UnityUpgradable)’
Errors:
Assets/JustAmbience.cs(7,23): error CS0308: The non-generic method `UnityEngine.Component.GetComponent(System.Type)’ cannot be used with the type arguments

But I did!

You did not read the error message properly. Component.audio is deprecated, and so you will also get the error when you use Component.audio.GetComponent(). Use GetComponent() on your own component (your script) directly. That is, drop the “audio.” part.

Chance this line

audio.GetComponent<AudioSource>(backgroundMusic);

To this this

audio.GetComponent<AudioSource>().Play (backgroundMusic);

Solve this your problem.

Also, make sure that you have added an Audio Source to the same game object that the script is attached to.

I am also new to this but I finally got it to work on a trigger (which was my objective).

  1. I attached an audio source to the object and the clip to the audio source.
  2. I added this line of code to my script (also attached to the same game object)

GetComponent().Play();

This worked for me and is the only one of the suggestions in here that compiles with my version of unity.

Good Luck!

2 Likes