Hi im kinda confused on this im starting to learn csharp and am trying to make a door open when a key is pressed within the box colider trigger this is what i have so far but how do i get the trigger working so that when the is pressed inside the trigger
using UnityEngine;
using System.Collections;
public class Door : MonoBehaviour {
private int m_LastIndex;
public void PlayDoorAnim ()
{
if(!animation.isPlaying)
{
if(m_LastIndex == 0)
{
animation.Play("DoorOpen");
m_LastIndex = 1;
}
else
{
animation.Play("DoorClosing");
m_LastIndex = 0;
}
}
}
}
Add a script to your GameObject with the trigger box collider. Inside the script, add the OnTriggerEnter() function. This will be called when a collider enters the trigger area. So if the collider that has entered the trigger is the player, you want to call the PlayDoorAnim() function.
The following (untested) code shows how to do this assuming that your player has the tag “Player”. It also assumes that your trigger GameObject has a collider attached with the “isTrigger” field set to true.
using UnityEngine;
using System.Collections;
public class DoorTrigger : MonoBehavior
{
public GameObject door;
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Player")
{
door.GetComponent<Door>().PlayDoorAnim();
}
}
}
Edit: You can also use OnTriggerExit() to detect the player leaving the trigger area.
See the scripting reference:
OnTriggerEnter
OnTriggerExit