Levers and Switches
In today’s blog post, we’ll be looking at triggering levers and switches using interactable events.
Setting up animations
We’re gonna tackle the light switches first. The first thing we need to do is to create animation clips for that represent the on and off states of the switch.
Then we create an animator controller for the switch and create transitions between the two states.
To switch between the states, we need to add a bool parameter called “SwitchOn” which is set to false by default.
Now we’ve set up the animations for the light switches, we can repeat the process for the levers.
Adding triggers
Colliders
To be able to interact with switches and levers, we need to add a Box Collider (Is Trigger should be unchecked) and an XR Simple Interactable component.
Scripting
To trigger the switch/lever animations I’m gonna create a simple script called Controllers.
using UnityEngine;
public class Controllers : MonoBehaviour
{
[SerializeField] private Animator _animator;
public void ToggleSwitch()
{
bool currentSwitchState = _animator.GetBool("SwitchOn");
_animator.SetBool("SwitchOn", !currentSwitchState);
}
public void ToggleLever()
{
bool currentLeverState = _animator.GetBool("LeverOn");
_animator.SetBool("LeverOn", !currentLeverState);
}
}
In this script, we get the reference to the Animator component and create two public functions to toggle the state of switches and levers.
When we’re done with the script, drop it into the switch and lever objects and assign the Animator component. Here’s an example of one of the light switches:
XR Simple Interactable
Now that we have everything we need, let’s configure this component to trigger the animations. Let’s start with a light switch!
Firstly, we drop the collider into the Colliders field. Next, I want to flip the switch when hovering over it so under the Hover Entered event, we reference the Controller script component for this switch and select the ToggleSwitch function.
I’m gonna repeat the process for the levers but will be using the Activate event instead of the Hover event.
Testing
After we finish setting up, things should work as expected.