Script for open and close door animation with the same clic?

(watch video)

By clicking on the active door the door opening animation. I would now like it to close with the same click.
How can I do that? Is there a script that activates one animation and then starts another if it has already been activated?
Or do you have other solutions?

this is code I use:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;



public class OpenCloseDoor : MonoBehaviour {



Animator anim;



void Start()

{

anim = gameObject.GetComponent<Animator>();

}

void Update()

{

if (Input.GetMouseButtonDown(0))

{

anim.SetTrigger("open");

}



}



}

Just set a bool that says if the door is opened or closed. If it is closed, when you click you do the open animation, if the bool says it is open you run the closed animation.

private bool doorIsClosed = true;

void Update ()
{
    if (Input.GetMouseButtonDown(0))
    {
        if (doorIsClosed)
        {
            //run the door open animation here

            doorIsClosed = false;
        }
        else
        {
            //run the door closing animation here

            doorIsClosed = true;
        }
    }

}
1 Like

The above can be shortened by writing
doorIsClosed = !doorIsClosed;
But I reckon you can do this a better way.

What I recommend is having two animations in your animator, Opened and Closed. Set the default to closed. Then put a transition back and forth between Opened and Closed.

On you mouse click, call anim.SetTrigger(“Interact”);

So if the door is open and you trigger interact it will start the close, of its closed it will start the open.

Remembering the default is door closed, if you want the game to start with the dore open then just call anim.SetTrigger(“Interact”); in your Start() function.

1 Like

Here is the Animator example

3764746--314182--Untitled.png

Thankyou everyone! Very useful! My main problem is that, by modeling, I can make something graphically, but I have many shortcomings in programming c#. I’m trying to learn from the beginning.

1 Like

No worries man, I’m happy to help :slight_smile:

I’m happy :slight_smile:

Hey man,

I just realized with your first script posted. There is no distance check to ensure the player cant open the dorr from to far away. If you looking to achieve that here is some sudo that you can reference to get it working.

private into minDistance = 10;
private Transform playerTrans;

start()
{
    playerTrans = GameObject.FindByTag("Player").tranform;
}


Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        if (Vector3.Distance(this.gameObject.transform.position, playerTrans.position) <= minDistance)
        {
            //Do stuff Here
        }
    }
}

You’re opening the door on the wrong side… :grinch: (sorry :wink: )

Absolutely! I even better arrange the dimensions of the tower and door! :slight_smile:

REALLY REALLY THANK YOU MAN!!!

1 Like