Hello,
I have the following monobehaviour attached to my weapon to detect the other collider’s physicmaterial; run it in “clips.TryGetValue(x, x)”; outputting to a variable and then calling a method to play the audio while passing in the value found. I have a debug line before the TryGetValue call. This is running. It finds the material successfully. It seems I’m getting an exception error for the key not existing in the dictionary. However, it has been added on awake. I’ve tried multiple solutions. I’m going to try to print out a list of the keys and their values after I initialize everything right now.
Any help would be great. Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Snd_ImpactListener : MonoBehaviour {
public Dictionary<PhysicMaterial, AudioClip> clips = new Dictionary<PhysicMaterial, AudioClip>();
public AudioClip metalImpact;
public AudioClip woodImpact;
public AudioClip fleshImpact;
public PhysicMaterial metalMaterial;
public PhysicMaterial woodMaterial;
public PhysicMaterial fleshMaterial;
private AudioSource source;
private void Start()
{
if (!clips.ContainsKey(metalMaterial))
clips.Add(metalMaterial, metalImpact);
if (!clips.ContainsKey(woodMaterial))
clips.Add(woodMaterial, woodImpact);
if (!clips.ContainsKey(fleshMaterial))
clips.Add(fleshMaterial, fleshImpact);
}
private void OnEnable()
{
if (!GetComponent<AudioSource>())
{
source = gameObject.AddComponent<AudioSource>();
}
else
{
source = GetComponent<AudioSource>();
}
}
private void OnTriggerEnter(Collider collision)
{
PhysicMaterial materialFound = collision.material;
AudioClip clip;
Debug.Log("Hit detected. attempting to play sound ==> " + materialFound.name.ToString());
if (clips.TryGetValue(materialFound, out clip))
{
PlayRequestedAudio(clip);
Debug.Log("Played sound: " + clips[materialFound].name);
}
}
public void PlayRequestedAudio(AudioClip audio)
{
Debug.Log("Playrequestedaudio");
source.PlayOneShot(audio);
}
}