Hi, I am following the Will Goldstone book and part of it makes a collider on a door that should play a sound and animation when you get inside the collider. The collider needs to be a trigger though so you dont run into an invisible wall. My problem is when I check " is trigger" the audio doesnt play. If I uncheck “is trigger” I hit an invisible wall, and the audio plays as it should. Any thoughts? Here is the script:
private var doorIsOpen : boolean = false;
private var doorTimer : float = 0.0;
private var currentDoor : GameObject;
var doorOpenTime : float = 3.0;
var doorOpenSound : AudioClip;
var doorShutSound : AudioClip;
function Update ()
{
}
function OnControllerColliderHit (hit : ControllerColliderHit)
{
if(hit.gameObject.tag == "playerDoor" && doorIsOpen == false)
{
OpenDoor(hit.gameObject);
}
}
function OpenDoor (door : GameObject)
{
doorIsOpen = true;
door.audio.PlayOneShot(doorOpenSound);
}
When the collider becomes a trigger, OnControllerColliderHit events don’t occur anymore - OnTrigger events replace them. You should thus use OnTriggerEnter instead:
function OnTriggerEnter (other: Collider)
{
if(other.tag == "playerDoor" && doorIsOpen == false)
{
OpenDoor(other.gameObject);
}
}
Notice that the parameter passed to OnTrigger events is other: Collider, which means the other collider/trigger - these events are sent to both objects, and each one receive info about the other object.
OnTriggerEnter is your friend:
file:///Applications/Unity/Unity.app/Contents/Documentation/Documentation/ScriptReference/Collider.OnTriggerEnter.html
Use “OnTriggerEnter” rather than “OnControllerColliderHit”. And also use “OnTriggerExit” to shut the door.
private var doorIsOpen : boolean = false;
private var doorTimer : float = 0.0;
private var currentDoor : GameObject;
var doorOpenTime : float = 3.0;
var doorOpenSound : AudioClip;
var doorShutSound : AudioClip;
function Update () { }
function OnTriggerEnter(collider : Collider)
{
if(collider.gameObject.tag == "playerDoor" && doorIsOpen == false)
{
OpenDoor(collider.gameObject);
}
}
function OnTriggerExit(collider : Collider)
{
if(collider.gameObject.tag == "playerDoor" && doorIsOpen == true)
{
ShutDoor(collider.gameObject);
}
}
function OpenDoor (door : GameObject)
{
doorIsOpen = true; door.audio.PlayOneShot(doorOpenSound);
}
function ShutDoor (door : GameObject)
{
doorIsOpen = false; door.audio.PlayOneShot(doorShutSound);
}
Great, I will update the scripts. I suppose Will was just using some out of date code with the OnCollisionHit function that he put in the book. Thanks guys.