8: Adding sound effects

Step 1:
Slect the sound effect you want to use and import it into Unity. We used a door creak for this example and the file can be found on The Sound Bible here.

Step 2:
Add an Audio Source component to your box. Select the box in the scene view and in the inspector click the add component button gotto Audio > AudioSource. Now add the Sound effect you wish to use to the audio clip slot. Uncheck Play on Awake.
quest025

Step 3:
Now we need to add to our interactionControls script by finding the AudioSource component and setting it to play.

JS

#pragma strict

var B : GameObject;

function Start () 
{
    B.SetActive(false);
}

function OnTriggerStay(hit : Collider)
{
     if(hit.gameObject.tag == "BOX")
     {
           if(Input.GetButtonDown("Interact"))
          {
               var ani : Animator = hit.gameObject.GetComponent(Animator);
               ani.SetBool("OPEN", true);
               var AS : AudioSource = hit.gameObject.GetComponent(AudioSource);
               AS.Play();
               Destroy(hit.gameObject.GetComponent(Collider));
               B.SetActive(false);
          }
     }
}

function OnTriggerEnter(hit : Collider)
{
    if(hit.gameObject.tag == "BOX")
    {
        B.SetActive(true);
    }

}


function OnTriggerExit(hit : Collider)
{
    if(hit.gameObject.tag == "BOX")
    {
        B.SetActive(false);
    }
}

C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class interactionControls : MonoBehaviour {

public GameObject B;

// Use this for initialization
void Start ()
{

     B.SetActive(false);
}


void OnTriggerStay(Collider hit)
{

     if(hit.gameObject.tag == "BOX")
     {
          if(Input.GetButtonDown("Interact"))
          {
               Animator ani = hit.gameObject.GetComponent<Animator>();
               ani.SetBool("OPEN", true);
               AudioSource AS  = hit.gameObject.GetComponent<AudioSource>();
               AS.Play();
               Destroy(hit.gameObject.GetComponent<Collider>());
               B.SetActive(false);

          }
     }
}

void OnTriggerEnter(Collider hit)
{
     if(hit.gameObject.tag == "BOX")
     {
          B.SetActive(true);
     }
}

void OnTriggerExit(Collider hit)
{
     if(hit.gameObject.tag == "BOX")
     {
          B.SetActive(false);
     }

}

}

Casino Bet 365 is best casino in the world.

What's Next

Next up for Unity Snippets is a look at game development articles from across the web...

Free Templates - bigtheme.net
Popular Art Betting make bookies articles.