Hi, I can't start the audio when entering an area in 2D. I have a game object and here is the code attached to it. However, I can't attach the sound to the script on the Unity Inspector panel, or is there another way to do it? Thank you so much... Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayOnCollision : MonoBehaviour { public AudioSource audioSource; void OnTriggerEnter(Collider other) { if (other.tag == "Player" && !audioSource.isPlaying) { audioSource.Play(); } } }
then, I've tried this and didn't work... Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Audio : MonoBehaviour { public AudioSource onesynthesize; // Start is called before the first frame update void Start() { onesynthesize = GetComponent<AudioSource> (); } // Update is called once per frame void Update() { } void OnCollisionEnter (Collision collision) { if (collision.gameObject.tag == "soundtileone"){ onesynthesize.Play (); } } }
In your screenshot, onesynthesize is null because you didn't attach a sound to it. Do it in your project GUI, or write code that loads an existing AudioSource from disk. Looks like this thread has a proper example of scripting the playback of an AudioSource from the Resources folder.