I’ve been following an older course, so I am using Unity 2017.4.40f1. I want to use GetComponent() to access an AudioSource on an object, but the GetComponent() line seems to not even be called; the AudioSource I am targeting doesn’t show up in its slot in the Inspector when I run the game. As a temporary fix, I commented-out the GetComponent() line and just assigned the AudioSource manually via the Inspector, but when I started the game, the reference disappeared. A Null Reference Exception is thrown when the code tries to reference the AudioSource in question. I don’t have anything that would assign its value to null, or anything that would delete the component, and I am positive that the AudioSource is on the right GameObject.
Any help would be greatly appreciated. Here’s my code, with comments in important areas:
[SerializeField]
private AudioSource _audioSource; // The AudioSource I want to access. SerializeField added during debugging.
[SerializeField]
private AudioClip _winClip;
// Use this for initialization
void Start ()
{
_uIManager = GameObject.Find("Canvas").GetComponent<UIManager>();
_audioSource = GetComponent<AudioSource>(); // The line I used to try to access the component on the GameObject my script is attached to. I don't think it even got called, because the null-checking code below doesn't ever run. Either this, OR the reference is deleted after it is assigned. This seems more likely.
if (_uIManager == null)
{
Debug.LogError("UIManager of Canvas is null");
}
if (_audioSource = null) // Null-checking code for the component. This never runs.
{
Debug.LogError("AudioSource of Sharkman is null");
}
Debug.Log("WeaponShop Start method called"); // Debug statement added to see if Start() even runs. It does run.
}
// Update is called once per frame
void Update ()
{
}
private void OnTriggerStay(Collider other)
{
if (other.name == "Player")
{
_uIManager.TogglePurchasePrompt(true);
if (Input.GetKeyDown(KeyCode.E) && _playerHasCoin == true)
{
_uIManager.ToggleInventoryCoin(false);
ToggleFunds(false);
_audioSource.clip = _winClip;
_audioSource.Play(); // And here is where the Null Reference Exception leads to. I don't know why.
}
else if (Input.GetKeyDown(KeyCode.E) && _playerHasCoin == false)
{
Debug.Log("Insufficient funds");
}
}
}
This shows that the Audio Source is attached: