Home > Net >  Unity GetComponent not searching other objects
Unity GetComponent not searching other objects

Time:03-25

To be honest based on the documentation I cannot tell but should GetComponent<T>() search all objects in the scene for the component? I have a pub/sub setup and have various EmptyObjects in a scene named <name>Publisher ie WorldPublisher \ PlayerPublisher where I can attach various needed publishers.

My idea was that I could call GetComponent<KeyBindingPublisher>() and that would give back that script. However, I am getting a null so it cannot seem to find it from say the player GameObject.

I do not want to attach both pub/sub to the player GameObject that feels too tightly coupled.

I am currently doing this:

GameObject playerEvents = GameObject.Find("PlayerPublishers");
KeyBindingPublisher keyBindingPublisher = playerEvents.GetComponent<KeyBindingPublisher>();

Which does appear to work but that seems to tightly couple the subscriber script and UI which I was trying to avoid. I might not need to put a PlayerPublishers object so just want to be able to get a ref to the script without knowing all the objects.

CodePudding user response:

When you call GameObject.GetComponent, that will search for a matching component attached to the specific GameObject that you call it on. If you want to include other GameObjects in the search, you have a few options:

If you are searching for multiple objects, there are similar functions that return arrays of matches.

As you might imagine, casting a wide net can have an impact on performance. Searching the entire scene is ideally something that should be kept to a minimum.

If you are looking for exactly one instance of a KeyBindingPublisher that other scripts can reference across all scenes, you might look into a design pattern called a singleton. Here is an example from GameDev Stack Exchange that includes some code samples for achieving this in Unity3D.

  • Related