Skip to content

Volumes ‐ Interact volumes

Will Corby edited this page Mar 7, 2024 · 1 revision

Creating a custom interactable object in Unity is pretty easy. First of all, create a new empty GameObject as a child of the object you want to be interactable. Give the new object the following components:

  • Any base Unity 3D Collider (BoxCollider, SphereCollider, MeshCollider, etc.)
  • An InteractReceiver
  • Your custom interaction script.

image

(This image is from the mod Hearth's Neighbor, the Lake Planet Lever script is my custom interaction.)

In your custom interaction script, you'll need to create a function that occurs when an interaction happens and subscribe to an event in the InteractReceiver. Vanilla scripts call this OnPressInteract.

using UnityEngine;

public class InteractScript : Monobehaviour // Please do not actually name your class "InteractScript"
{
  private SingleInteractVolume _interactVolume; // This is the component that InteractReceiver inherits from

  private void Awake()
  {
    _interactVolume = this.GetRequiredComponent<SingleInteractVolume>(); 
    // As far as I can tell this is the same as GetComponent<SingleInteractVolume>(), but this is what base game scripts use
    _interactVolume.OnPressInteract += OnPressInteract;
    // Add any other events here.
    // For example, you can try "GlobalMessenger.AddListener("SuitUp", new Callback(OnSuitUp));" to subscribe to putting on your suit
  }

  private void OnPressInteract()
  {
    // Run your code for when you interact with something
  }

  // To Disable or Enable interaction, use "_interactVolume.DisableInteraction()" or "_interactVolume.EnableInteraction()" respectively
}

You'll also need to set your Interaction Text. To do that, set the Text ID of your InteractReceiver either in Unity or via code:

_interactVolume._textID = UITextType.HoldPrompt;

To do it in Unity, change the Text ID in the InteractReceiver component.

If none of the vanilla text prompts fit your needs, you can try using SingleInteractionVolume.ChangePrompt(string)

_interactVolume.ChangePrompt("Hold Sunglasses");

Sometimes, your interaction prompt may not show up. In my experience, this happens due to your Unity collider being disabled. Check to make sure nothing is disabling it, and make sure the GameObject isn't being disabled until the end of the frame (you can use the WaitUntilEndOfFrame function in a co-routine to make sure disabling happens after everything else).