Skip to content

Instantly share code, notes, and snippets.

@rsaenzi
Created September 11, 2021 03:53
Show Gist options
  • Save rsaenzi/64b094ef0291b711f56f77c037ade307 to your computer and use it in GitHub Desktop.
Save rsaenzi/64b094ef0291b711f56f77c037ade307 to your computer and use it in GitHub Desktop.
Script for Unity to play a sound when a Collider 2D is touched by another Collider 2D
//
// CollisionSound.cs
//
// Created by Rigoberto Sáenz Imbacuán (https://linkedin.com/in/rsaenzi/)
// Copyright © 2021. All rights reserved.
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Collider2D))]
[RequireComponent(typeof(AudioSource))]
public class CollisionSound : MonoBehaviour {
private AudioSource source;
void Awake() {
source = this.GetComponent<AudioSource>();
}
void OnCollisionEnter2D(Collision2D collision) {
if (source.clip != null) {
source.Play();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment