Hi all,
I have a gameobject with 2 scripts and an Audio Source component.
My first script is called BoardManager and it contains to following code:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class BoardManager : MonoBehaviour {
AudioManager audioManager = new AudioManager();
void start() {
audioManager.PlaySound("sound1");
}
}
The second script is called AudioManager and it contains the following code:
using UnityEngine;
using System.Collections;
public class AudioManager : MonoBehaviour {
public AudioClip sound1;
public void PlaySound(string soundName) {
AudioSource audio = GetComponent<AudioSource>();
if (soundName == "sound1")
audio.PlayOneShot(sound1);
}
}
When the BoardManager script calls the PlaySound function from the AudioManager script it gives a NullReferenceException error on the line:
AudioSource audio = GetComponent<AudioSource>();
If the PlaySound function is in the BoardManager script, it works fine.
Why can’t the AudioManager script find the AudioSource component if it is called from the BoardManager script if they are in the same gameobject and the Audio Source is next to both of them?
Is there a way to fix this?
Thanks.