Hi Unity users.
I got a problem, i’m new on Unity 3D and i’m trying to use an animation for my door.
Well, first of all, i don’t know how to make a start or what i need, but now my question is.
If my player is walking to a door that i made and i press a key ( by example ‘D’ ). The door should open with an animation and it stays open. Can someone help me please.
I was searching for it, or something like that. But i found nothing.
I have seen the comment you put on the above answer by ChrisD, so I will answer those questions and provide some example code.
First, in order to make sure that the player is near the door, you must have a Box configured so that it will cover the area that is considered “close” in your game. Then, you must go into the BoxCollider, and set the “Is Trigger” option. This will make it so that it does not act like a wall. Next, you do not want the box to be visible. So, go back to the Box GameObject, and remove the MeshRender component.
Next, make a new script. I will use JavaScript, because that seems like what you are using. Unfortunately, I script mostly in C#, and have forgotten some of the syntax.
var DoorGameObject : Transform; // This is a reference to the door GameObject that has your animation
private var HasTriggerBeenUsed : boolean = false; // This is to make sure that the button is not repeatedly pressed.
private var setTrigger : boolean = false;
function OnTriggerStay() {
if (Input.GetKeyDown("d") && !HasTriggerBeenUsed) {
DoorGameObject.animation.Play("DoorHor");
setTrigger = true;
}
else if (Input.GetKeyDown("d") && HasTriggerBeenUsed) {
DoorGameObject.animation.Play("DoorClose"); // Insert name of DoorClose animation instead of that
setTrigger = true;
}
if (setTrigger) { HasTriggerBeenUsed = !HasTriggerBeenUsed; }
}
This script needs to be attached to the Box object that you created at the beginning. The variable, DoorGameObject needs to be assigned to the object that has your door on it.
I think I covered everything, but if there is something I forgot, please leave a comment.
To get it to trigger (if, say you wanted to walk up to it and press a ‘use’ key), you’d check if your player was within range, then check if the key is pressed.
Hope this helps!
Additionally, try following along with some tutorials on the Unity website or watchign a few on youtube - it really helps.