Search Unity

Question Toggle Door animation - Open door / Close Door

Discussion in 'VR' started by TheMartsy, Jan 17, 2023.

  1. TheMartsy

    TheMartsy

    Joined:
    Dec 27, 2017
    Posts:
    28
    I am using Unity 2021 URP
    XR Toolkit

    I am trying to write a script for doors when I touch the collider or put laser on the door I want the animation to start and when I do it again it closes. Basically toggle between both and somehow I cant figure out how to achieve that with VR. Can somebody please help me? Next step after that is introducing different lighting according to in what state is the door.

    Any help appreciated.
     
  2. PenProd

    PenProd

    Joined:
    Dec 17, 2022
    Posts:
    171
    First, add an Animator object to your door. Create two animations. One that opens the door, the other that closes the door. Call them "OpenDoor" and "CloseDoor".

    Next, add the following script to your door and save it as OpenCloseDoor.cs (it must have the same name as the class in the script):

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class OpenCloseDoor : MonoBehaviour {
    6.   private Animator doorAnim;
    7.   private bool doorOpen = false;
    8.  
    9.   public void ToggleDoorState() {
    10.     doorAnim = gameObject.GetComponent<Animator>();
    11.     if( !doorOpen ) {
    12.       doorAnim.Play( "OpenDoor" );
    13.     } else {
    14.       doorAnim.Play( "CloseDoor" );
    15.     }
    16.     doorOpen = !doorOpen;
    17.   }
    18.  
    19. }
    Next, add a simple Interactable to your door. Make sure the Interaction Layer Mask is set to the same layer your door is in. Under "Activated" click the + sign (to add to the list). Click and Drag your door object to the Object field. Click in the "No Function" field, hover over "OpenCloseDoor" and in the menu that appears, click "ToggleDoorState()".

    That's it.
     
  3. TheMartsy

    TheMartsy

    Joined:
    Dec 27, 2017
    Posts:
    28
    Thank you for the response. How do I go about setting up both animations in animator? Do I need a trigger?
     
  4. PenProd

    PenProd

    Joined:
    Dec 17, 2022
    Posts:
    171
    The trigger is in the Interactable. Have you added the XR Interaction Toolkit to your project?