Hello! I’m working on a game and I’m struggling with triggers. Here’s what should be happening:
The player enters a trigger. When inside the trigger he press ‘e’. An animation should start playing.
My script isn’t working and I want to use multiple triggers in my game; each for a different animation of different objects. Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
That’s because you’d need to be lucky and hit the key in the exact one physics update in which you Enter the trigger. This is not impossible, but the probability is not very high as well.
The first thing to think about is the OnTriggerStay method, however, keep in mind:
Physics-based callbacks run in the physics update, which does not happen in a 1:1 ratio to the Update methods. The result is unreliable input behaviour during the physic updates. You may miss input.
What you should probably do is using the Enter method to enable your Update-based input and the Exit method to disable it.
Something like this would work like Suddoha explained. I personally don’t really like the fact that in this
case you are handling input inside an item like a chest or in this case the fridgedoor trigger. I would rather let the player know that he is inside of a trigger. And let all the input be handle by the player in 1 class. So when you press E the player says to all triggers he’s in that they should do their action.
But just to get started and not too overflow you with information the code below fixes your current script.
Maybe there’s a way to detect when the player (or controller in vr) is near an object? so I can use something like distance from my controller to a gameobject and check if it’s <= xx ?
The trigger solution should work. There must be an issue with your setup of the scene or some other settings.
But I agree with @Jildert_1 , once you get this to work you should probably think about handling input somewhere else and not in these scripts.
This won’t work in most cases, because 1) you shouldn’t check Input in any part of the physics-cycle and 2) Enter will only be called in a single run.
You should add a helper field, for instance a boolean, that you set to true upon entering, and false upon exiting. Then, use that helper field in Update to check whether you’re currently in that trigger. If so, you check the Input additionally.