- Home /
How to add sound when a door opens in unity 3d?
i have a script that can make a door open but i don't have any sound.
here is the script
var smooth = 2.0; var DoorOpenAngle = 90.0; private var open : boolean; private var enter : boolean;
private var defaultRot : Vector3; private var openRot : Vector3;
function Start(){ defaultRot = transform.eulerAngles; openRot = new Vector3 (defaultRot.x, defaultRot.y + DoorOpenAngle, defaultRot.z); }
//Main function function Update (){ if(open){ //Open door transform.eulerAngles = Vector3.Slerp(transform.eulerAngles, openRot, Time.deltaTime smooth); }else{ //Close door transform.eulerAngles = Vector3.Slerp(transform.eulerAngles, defaultRot, Time.deltaTime smooth); }
if(Input.GetKeyDown("e") && enter){ open = !open; } }
function OnGUI(){ if(enter){ GUI.Label(new Rect(Screen.width/2 - 75, Screen.height - 100, 150, 30), "Press 'E' to open the door"); } }
//Activate the Main function when player is near the door function OnTriggerEnter (other : Collider){ if (other.gameObject.tag == "Player") { enter = true; } }
//Deactivate the Main function when player is go away from door function OnTriggerExit (other : Collider){ if (other.gameObject.tag == "Player") { enter = false; } }
if any one can make a new script of add on to mine... that would be awesome. thanx!!
Step 1 : read this page : http://answers.unity3d.com/page/newuser.html
For any help, please format your code. You can do this by highlighting all your code, then clicking the 10101 button at the top of the edit window.
Watch : http://video.unity3d.com/video/7720450/tutorials-using-unity-answers
Answer by GamingNewBie · Apr 17, 2013 at 05:41 AM
private void playSound(Transform transform, AudioClip clip)
{
var soundObject = new GameObject("Sound Object"); // Creating new game object to play sound
AudioSource audioSource = soundObject.AddComponent(typeof(AudioSource)) as AudioSource; // Attaching audio source to the game object
audioSource.volume = 1f;
audioSource.pitch = 1f;
audioSource.clip = clip;
soundObject.transform.position = transform.position; // positioning sound object to the doors position
audioSource.Play();
Destroy(soundObject, clip.length + 0.1f); // Destroying sound object
}
i hope this help.