Firstly, if you want to know when one set of bounds are wholly inside another one, don't test for intersection - that will return true even if the two bounds just barely touch.
The existing Contains
method only works for points, but we can add our own as an extension method for convenience:
public static class BoundsExtension {
// Note I skipped Z since you seem to be working in 2D.
// The Bounds struct is shared between both 2D & 3D uses,
// so we can write explicit Contains2D / Contains3D cases if needed.
public static bool Contains (this Bounds container, Bounds other) {
return container.min.x <= other.min.x
&& container.min.y <= other.min.y
&& container.max.x >= other.max.x
&& container.max.y >= other.max.y;
}
}
Next, it's important to remember that struct
instances like Bounds
are what's called a "value type" in C# - like booleans, numbers, and enumrations. That means that when we read them into a variable, we're taking a snapshot or shallow copy of their current value.
This is in contrast to "reference types" like class
instances, where reading them into a variable means storing a reference to the existing live instance, rather than copying its current contents.
(This also means a struct
can't be null
, only hold a default value - so that null
check on the bounds is not meaningful here. You could use Nullable structs that hold an extra flag to express "no value set" but here we have better solutions)
So, if we want to keep track of where our objects are now, we first need to store references to the reference types we care about. Since we need a Renderer
specifically to get bounds data from, we can make that explicit in our script's public variables - Unity will enforce this in the Inspector, so I can't accidentally assign a GameObject
that has no Renderer
attached into these fields.
(You can also get bounds from a Collider2D
depending on your needs)
public Renderer container;
public Renderer contents;
Then we can ask for the current value of the bounds struct
each frame when we want to do the test:
void Update() {
// Doing a null check on the references tells us if we forgot to set them,
// or if either of the Renderer components have been destroyed
if(container == null || contents == null)
return;
// Compare our Renderers' current bounds using our shiny new Contains method.
if(container.bounds.Contains(contents.bounds)) {
Debug.Log("We Good");
}
}