Created
September 11, 2021 03:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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