mavericks
mavericks

Reputation: 115

Play sound when other object(ball) hit cube

using UnityEngine;
using System.Collections;

public class audio : MonoBehaviour
{
  public AudioClip hitsound;

  void  Update ()
  {
  }

  void  OnTriggerEnter2D (Collider2D other)
  {
    if (other.tag == "Ball")
    {
        GetComponent.<AudioSource>().PlayOneShot (hitsound);
    }
  }
}

I assign .mp3 file to inspector, and also, I added Audio Source component but I can't hear hit sound. Cubes which need to be destroyed is moving during game. I added that script and audio source component on parts which are not moving and when ball hit that non-moving parts, sound is playing (every time).

I hope that someone can help me with this.

Thanks and kind regards

Upvotes: 0

Views: 150

Answers (1)

Bill Trikojus
Bill Trikojus

Reputation: 39

YOU HAVE A TYPO

GetComponent.<

SHOULD BE

GetComponent<


Doesn't the . after GetComponent give you an error?

Anyway, make sure your colliders are set as triggers (checkbox on component).

Also I think Unity recommend using CompareTag() instead of ==.

It's worth putting a Debug.Log into the OnTriggerEnter2D to see if that is even firing.

Finally, make sure your colliders are the 2D versions, not just the regular colliders.

Upvotes: 1

Related Questions