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;
}
}
}
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.
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.
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
}
}
}