Simple Door Opening/Closing Script Issues

Hey there,
Sorry in advance, this should be rather easy to do and my script’s gonna make your eyes probably bleed, but I don’t know much about C#.

I have the following script on my door pivot, and I’m trying to simply open the door onTrigger and have it closed aswell. I tried using both OnTriggerEnter & OnTriggerExit, but I ended up having the door close and open itself dozens of times per second.

My latest script (beware):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoorAnim : MonoBehaviour
{
    private Animator myDoor;
    public bool isOpen;

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player") && !isOpen)
        {
            myDoor = GetComponent<Animator>();
            myDoor.Play("DoorOpen");
            transform.GetChild(0).gameObject.GetComponent<MeshCollider>().enabled = false;
            isOpen = true;
        }
        else if (other.gameObject.CompareTag("Player") && isOpen)
        {
            myDoor.Play("DoorClose");
            isOpen = false;
            transform.GetChild(0).gameObject.GetComponent<MeshCollider>().enabled = true;
        }
    }

}

If anyone could help me out with this, I’ve been searching answers and pre-made scripts for literally hours and couldn’t get anything to work, sadly.
Thank you.

EDIT:
The Box Collider (with trigger) is set as follow (on the door pivot itself):

What does your Animation tree look like?

I ended up putting a box collider outside the door and put the trigger script on it instead of the door itself. Works much better, although it can sometimes be a bit buggy. The door opens and stays open once inside the house and will close back when re-entering the box collider which is in front of the door, outside.

This isn’t perfect at all, so if anyone has something better to suggest, I’d be thankful.

@RadRedPanda :

What did your code look like when you were doing both OnTriggerEnter and OnTriggerExit?

1 Like

Because you’ve asked it to do that. You’re toggling the door between open and closed when you first touch the trigger. You have to exit the trigger and enter it again to toggle it. I’m not sure why you’d want that.

As above, you’d use entering the trigger to open the door and exiting the trigger to close the door. Have the trigger span both sides of the door.

TBH I’m not sure why this isn’t obvious in terms of pure logic, ignoring the details of how to do it in code. :slight_smile:

Tried again with both of them and, for some reasons, it worked correctly this time.
Seems helpful sometimes to rewrite a code and pay more attention it seems! Thanks for your time.

Someone had a bad day. :slight_smile:

Glad you got it working.