Interacting with objects

I am new to unity and I was trying to think of a way to have a player be able to interact with objects in my game without using a long box with trigger set in it. For example when you look at a door in a game and it says press “e” to open, I’m looking for how to do something like that.(JavaScript preferably)

Ultimately, you’re going to need some mechanism that lets the player script(s) know when there’s something they can interact with.

Generally, that’s going to come down to some sort of proximity check:

  • OnTriggerEnter() is quick and simple: attach a trigger collider to each interactive object, and use layers, tags, or script components to handle hooks as characters enter those triggers.
  • Physics.OverlapShere() and similar functions can allow to “poll” for colliders within a particular area; you could periodically check for interactive objects near a character, or for characters near some other object.
  • FindGameObjectsWithTag() or FindObjectsOfType() could potentially allow you to build a list of interactive objects in your scene; you could then have those scripts periodically check for proximity.

Honestly, the first method is probably the most straightforward and performant. You seem to be looking for other options, though, so there’s what I’ve got off the top of my head.

In addition to the methods mentioned by rutter, you could also perform a raycast forward from the player. If the raycast hits an object you have tagged “usable object” the you can make a GUI call to show the words “press e to use.” Finally if you wanted to you could switch the object’s shader to make it highlighted. I would recommend this shader on the comunity wiki.

To actually make the object do something when you press “e” you would need to have some code that runs when the key is pressed that checks if the raycast had hit any usable objects and then calls some function on the object.