- Home /
Question by
Hristiyan2021 · Apr 09 at 10:49 AM ·
trigger
Need help with a code
Hey guys, I am currently working on a scene where an object has to open a door using a trigger function. For now, I managed to make the animations for both opening and closing and wrote the code about the open function, and it works. But I have a problem with closing the door. I added a "hinge" with collider, so when the player is too close, by pressing a button, he would open the door. I tried to rewrite the same function with another "bool", but that didn't work. Does someone know what I can write? Thank you in advance!
lcovxar.jpg
(168.7 kB)
jznpglb.jpg
(111.3 kB)
Comment
Answer by Caeser_21 · Apr 09 at 11:46 AM
If you are trying to make a door open/close script you can try :
Animator anim;
private bool IsInRange;
private bool IsOpen;
private void Start()
{
anim = GetComponent<Animator>();
}
private void Update()
{
if (IsInRange)
{
if(Input.GetKeyDown(KeyCode.E))
{
if(IsOpen)
{
Debug.Log("Door has been closed");
anim.Play("DoorClose");
IsOpen = false;
}
else
{
Debug.Log("Door has been Closed");
anim.Play("DoorOpen");
IsOpen = true;
}
}
}
}
private void OnTriggerEnter(collider other)
{
if (other.CompareTag("Player"))
{
IsInRange = true;
}
}
private void OnTriggerExit(collider other)
{
if (other.CompareTag("Player"))
{
IsInRange = false;
}
}
NOTE : Make sure you have an animation called "DoorClose"...