I am trying to create a sound when the player collides with a key and i am hearing nothing. this is what i have Code (CSharp): using UnityEngine; using System.Collections; public class PickupTrigger : MonoBehaviour { public AudioSource keysource; void Start() { keysource = GetComponent<AudioSource>(); } void OnTriggerEnter(Collider col) { // Task 2 part 1 code goes here if (col.tag == "Player") { keysource.Play(); GameManager.Instance.pickup(); Destroy(gameObject); } } }
I had a whole thing about putting in Debug.Log's in various places to debug it, then I noticed that you're destroying the gameObject, which means the AudioSource is getting destroyed. An AudioSource can't make sound if it no longer exists. I recommend using AudioSource.PlayOneShot. Don't have an AudioSource on the pickup at all, just have a reference to the AudioClip itself and pass it into PlayOneShot.
Use Debug.Log to confirm that the code that you expect is executing, and that col.tag actually equals "Player" https://forum.unity.com/threads/tips-for-new-unity-users.701864/#post-5057741
I still can't hear anything Code (CSharp): using UnityEngine; using System.Collections; public class PickupTrigger : MonoBehaviour { public AudioClip impact; AudioSource keysource; void Start() { keysource = GetComponent<AudioSource>(); } void OnTriggerEnter(Collider col) { if (col.tag == "Player") { keysource.PlayOneShot(impact); GameManager.Instance.pickup(); Destroy(gameObject); } } }
this does work because the key does get picked up by the player, i just wanted a sound to play when it does
I have put this Code (CSharp): AudioSource.PlayClipAtPoint(keysource, new Vector3(-11.816, 11.093, -155.782)); but it is telling me that it cannot convert from double to float but those are my coordinates
There are two data types for decimal-point data, "double" and "float". double supports larger numbers and/or more precision, but uses more memory. Unity uses float everywhere because that's usually as much precision as is needed for games, and memory is generally at more of a premium. In C#, decimal numbers are by default assumed to be doubles. To force it to be a float, you can put "f" at the end of the number: -11.816f, for example. That'll fix the error. But, you should not really be typing numbers into the script in this situation. You want to use the object's own position, so just feed that variable straight into the function: Code (csharp): AudioSource.PlayClipAtPoint(impact, transform.position); (also, that function wants the clip, not the source)
I'm a big fan of instantiating an effects GameObject at the point of impact, and then attaching any effects you want to play after the primary GameObject is destroyed to this effects object. In this case an audio source, but you'll often want things like particle effects, point lights, etc, at that same point. These also make good candidates for object pooling.