Find objects referencing some other object.

So I have found myself needing a way to determine what GameObjects in a scene have Components that reference some other GameObject in the scene (or its components). I wanted something where I could easily right click a gameobject in the hierarchy, select ‘find references to’, and have all of them highlighted for me.

I need this because when using my ‘t & i’ system, or my new AI Behaviour Tree system, I reference gameobjects a lot. And I’d like to reverse look up who is referencing my various scripts.

See:

Take for instance here, when the player presses the A button near this post it sends a signal to E.OnPress, E.OnPress plays a sound effect as well as daisy chain triggers E.Open, E.Open is the event handler for the gate behind the switch and will animate the gate open.

Now lets consider that one designer had set this up. But they had set it up so various things could trigger E.Open. Other than this Switch here, maybe there’s an alternate Switch somewhere else, or maybe it opens after a timer, etc etc. There could be numerous things referencing E.Open.

I’d like to be able to right click E.Open, select ‘find references to’, and all other GameObjects with scripts on them that reference it are highlighted.

So first I need to add a context menu entry, but, alas, just adding something to the Hierarchy Context menu isn’t directly available.

So I wrote this to get a custom context menu to pop up if you hold ctrl and left click:

Now, if I place a MenuItem attribute on a function, and declare its path to start with “CONTEXT/ALT/”, it’ll end up in this custom context menu.

And so now I could write my script to search for everything.

Writing the script was a bit cumbersome and slap dash. I’m literally getting all components in the scene, reflecting the fields off of them (and recursively the fields of those fields), and testing if the value stored in it is the object we’re searching for.

Figured I’d shared it, as well as see if anyone has a better idea of doing this. I wanted to maybe try searching all the serialized data for the scene… but didn’t know how to get my hands on that data easily.

1 Like

So no one knows of a cleaner way of accomplishing this?