What am i doing wrong

I am trying to play soundclip from resources file

private AudioSource source;
private AudioClip cp;

// Use this for initialization
void Start ()

AudioSource source = gameObject.AddComponent();
AudioClip cp = Resources.Load (“crowd”) as AudioClip;

update method
source.PlayOneShot(cp);

I am getting object not set to instance of object error but i have already assigned cp as audio clip

Please tell us the line the error is on. Or else paste the actual error message so that we can see the line number on it, plus paste your exact code in tags.

Also, are you sure there’s an audio clip called “crowd” inside a “Resources” folder? I’m not sure what happens if you don’t, but perhaps the Load() command is simply returning null.

Its on the line

source.PlayOneShot(cp);

NullReferenceException: Object reference not set to an instance of an object
cont.Update () (at Assets/scripts/cont.cs:19)

I do have crowd inside resources. How do i check if load is returning null

immediately after loading write: Debug.Log("loaded? " + (cp != null));

said true

So the clip is loading; the only other thing on that line which could be null is the audio source, so your problem has something to do with that.

(more generally, notice how we’re systematically going through steps? this is what you do to debug this kind of issue in the future)

You have correctly declared properties (aka fields) called “source” and “cp”. But then in your Start method, you ignore these and instead create local variables with the same names. You assign your AudioSource and AudioClip to these local variables, the Start method ends, those variables go poof, and the whole while, your properties were never touched.

To fix this, change your Start method like so:

        source = gameObject.AddComponent<AudioSource>();
        cp = Resources.Load ("crowd") as AudioClip;

Now, because you haven’t specified a type, the compiler knows you mean to refer to the already-declared properties rather than make new local variables.

1 Like

Ahh thanks it works now, didnt knew it would create duplicates

doh I missed that, subtle bug