Keep character inside of an objects bounds

I am trying to restrict my character’s movement to inside the bounds of another object, but I am having no luck. I want to move my character to a position inside the other object and not allow the player to leave that object’s bounds. How can I do this?

I see three main options:

  1. Triggers

Add a collider to the “other” object. Make it a trigger. Attach a script to it. In that script you’ll get OnTrigger* events (e.g., you’ll probably be interested in OnTriggerExit).

You can move your character however you need to when you get the OnTriggerExit event.

  1. Physics

Add a rigidbody and a collider to your character. Now it’ll collide with any (non-trigger) colliders in the scene. Colliders can’t be inside of each other, so you’ll need to surround your object with a number of colliders (e.g., to cover all sides of a box you’d need six).

This way requires more setup, but you get the benefit of physics handling the movement for you (at least partly).

  1. Hybrid

One interesting way to approach this would be to use triggers (option 1) to detect when you character is out-of-bounds, then dynamically spawn a physics collider positioned so that they’ll bounce off it (similar to option 2, but dynamic).

That would avoid the setup overhead of creating six colliders, and would handle dynamic situations better. But getting the spawning working correctly will be painful I’d guess =]

Thanks, both of you. I’m going to go with the hybrid option because i want my scenarios to be dynamic and modular in that I only need to place little amounts of objects to perform tasks. I think i will instantiate a collider on 4 sides of the bounds (i restrict my characters movement on the z axis in this state already), but can you provide any info on getting the dimensions of an object in world space?

For anyone looking for a cleaner, modern solution to this:
You can use Composite Collider 2D components.
First, create an empty object and add the Box or Polygon Collider 2Ds that you need to form the desired shape.

Then, add a Composite Collider 2D component, and check the Used By Composite option on your Collider components. That will combine the meshes. Now you will have the ability to modify some new settings for your collision, including setting the geometry type of your colliders to Outline. That way they act as a 2d wall.

Finally, here is the completed properties, with the most important ones highlighted.