- Home /
On enter door open
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;
}
}
}
}
Answer by randomperson42 · May 06, 2014 at 06:33 AM
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
NullReferenceException: Object reference not set to an instance of an object dooropen.OnTriggerEnter (UnityEngine.Collider col) (at Assets/dooropen.cs:12)
this also happens with the asset simple door open asset that i bought to try and get it to work
You need to make sure that you set the door GameObject in the inspector. Inside Unity, you select the GameObject that has the DoorTrigger (or equivalent) script, then simply drag-and-drop your door object onto the door variable slot.
ive got my door ive put a box colider on it set as trigger and expanded it a bit is that what you mean?
I see what you mean. I thought you had your collider trigger on a separate object. I meant for you to put the script above on a separate collider object with a reference to the door. This is probably what you want since a door animation could cause problems with changing the trigger area, if that makes sense.
So remove the above script from your door, and put it on a separate GameObject with a trigger collider. Then set the door variable to your door object.