...

/

Interaction Advanced II: Custom State Management

Interaction Advanced II: Custom State Management

Learn how to manage custom states for Interactable objects in VR, including adding audio and visual effects, adjusting line visuals, and implementing haptic feedback.

Interactable custom state management

In this lesson, we’ll focus on adding audio to our saber. To make the experience more immersive, we want to play two different sounds: one while the saber glides toward the user and the other when the user finally grabs it. To achieve this, we’ll need to maintain different states for the Interactable, because simply relying on Interactable events alone may not suffice. So, let’s dive in and learn how to create an even more engaging experience with audio!

Press + to interact
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
public class SaberEventHandler : MonoBehaviour
{
public GameObject HoverVFX, SelectVFX;
public AudioSource SaberGlidingAudio, SaberGrabAudio;
public Transform HandleTransform;
public float GrabRange;
private Transform InteractorTransform;
private bool StateIsGliding, StateInHand;
private void Start()
{
InteractorScript = null;
StateIsGliding = false;
StateInHand = false;
}
private void Update()
{
if (StateIsGliding)
{
if ((InteractorTransform.position - HandleTransform.position).magnitude <= GrabRange)
{
SaberGlidingAudio.Stop();
SaberGrabAudio.Play();
StateIsGliding = false;
StateInHand = true;
}
}
}
public void OnSelectEntered(SelectEnterEventArgs args)
{
InteractorTransform = args.interactableObject.transform;
StateIsGliding = true;
StateInHand = false;
SaberGlidingAudio.Play();
}
public void OnSelectExited(SelectExitEventArgs args)
{
InteractorTransform = null;
StateIsGliding = false;
StateInHand = false;
}
public void SpawnHoverVFX()
{
Instantiate(HoverVFX, transform).SetActive(true);
}
public void SpawnSelectVFX()
{
Instantiate(HoverVFX, transform).SetActive(true);
}
}

To see this in action, attach the OnSelectEntered and OnSelectExited event handlers with the “First Select Entered” and “Last Select Exited” events, respectively.

You can hear the audios triggered on gliding and grabbing in the video below:

Task: Remove line visuals when the saber is grabbed

Lastly, we’d also want that once we’ve selected the saber, the line visuals turn off, but they turn back on whenever we ...