Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question PlayOnCollision

Discussion in 'Audio & Video' started by gurkanmihci, Jul 8, 2020.

  1. gurkanmihci

    gurkanmihci

    Joined:
    Apr 4, 2020
    Posts:
    3
    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):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5.  
    6. public class PlayOnCollision : MonoBehaviour
    7. {
    8.     public AudioSource audioSource;
    9.  
    10.     void OnTriggerEnter(Collider other)
    11.     {
    12.         if (other.tag == "Player" && !audioSource.isPlaying)
    13.         {
    14.             audioSource.Play();
    15.         }
    16.     }
    17. }
    18.  
    19.  
     

    Attached Files:

  2. gurkanmihci

    gurkanmihci

    Joined:
    Apr 4, 2020
    Posts:
    3
    then, I've tried this and didn't work...


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Audio : MonoBehaviour
    6. {
    7.  
    8. public AudioSource onesynthesize;
    9.     // Start is called before the first frame update
    10.     void Start() {
    11.         onesynthesize = GetComponent<AudioSource> ();
    12.        
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update() {
    17.     }
    18.         void OnCollisionEnter (Collision collision) {
    19.            
    20.             if (collision.gameObject.tag == "soundtileone"){
    21.              onesynthesize.Play ();
    22.            
    23.             }
    24.     }
    25. }
     

    Attached Files:

  3. unitybru

    unitybru

    Unity Technologies

    Joined:
    Jan 28, 2020
    Posts:
    225
    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.