I have two scripts. EnemyTriggerScript.cs which I want to handle collision detection and play audio from my AudioManagerScript.cs.
The code below works if I use GameObject.Find but will not work when I provide an audioManagerGameObject and do a GetComponent on it.
I have verified that my GameObjects are assigned to the respective scripts in the inspector.
The error I get is “Unassigned Reference Exception: The variable audioSource of AudioManagerScript has not been assigned. You probably need to assign the audioSource variable of the AudioManagerScript script in the inspector.”
Obviously this is telling me what is wrong, however I thought that initializing my audioSource in the AudioManagerScript was doing that???
audioSource = GetComponent();
I also looked throughout the inspector and specifically at the AudioManagerGameObject and AudioManagerScript.cs which I am not sure how to assign an audio source even if I made my variable public.
I am still really new to all of Unity and C# so I understand this is probably something simple but I have been searching for hours on end trying to solve this, any help would be appreciated.
EnemyTriggersScript.cs
using UnityEngine;
using System.Collections;
using UnityEditor;
public class EnemyTriggersScript : MonoBehaviour
{
[SerializeField] private GameObject audioManagerGameObject;
private AudioManagerScript audioManagerScript;
void Start ()
{
// This is the GetComponent that is not working
//audioManagerScript = audioManagerGameObject.GetComponent<AudioManagerScript>();
// This is working
audioManagerScript = GameObject.Find("AudioManagerGO").GetComponent<AudioManagerScript>();
}
void OnTriggerEnter2D(Collider2D collision)
{
// checking for collision with shield2
if (collision.gameObject.name == "shield2")
{
audioManagerScript.AudioPlayPlayerShieldDown();
}
}
AudioManagerScript.cs
using UnityEngine;
using System.Collections;
public class AudioManagerScript : MonoBehaviour
{
[SerializeField] private GameObject audioManagerGameObject;
[SerializeField] private AudioClip audioClipPlayerShieldDown;
private AudioSource audioSource;
void Start ()
{
audioSource = GetComponent<AudioSource>();
}
public void AudioPlayPlayerShieldDown()
{
audioSource.PlayOneShot(audioClipPlayerShieldDown, 1);
}
}