Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How do I get the right local player GameObject in a GameObject parent?

Discussion in 'Netcode for GameObjects' started by Eigulite, Jul 21, 2023.

  1. Eigulite

    Eigulite

    Joined:
    May 13, 2022
    Posts:
    60
    I have a gameObject called Clients that contains all the connected player gameObjects. How do I get the right local player GameObject through a script of an object that is in another GameObject? Just like you would find GameObjects with:
    GameObject obj = GameObject.Find("/");
    Thanks!
     
  2. jackward84

    jackward84

    Joined:
    Jan 26, 2017
    Posts:
    87
    You can search all of a gameobject's children and get back a list of a certain component, you can do it with something like:
    var players = parentGameObject.GetComponentsInChildren<Player>();
    which will return an enumerable of all the
    Player
    components that exist under that gameobject.

    If you don't care about performance, you can do a global search:
    var players = GameObject.FindObjectsByType<Player>();
    .

    Neither of these are a very performant way of searching for a particular player, but the first option is much better than the 2nd to just fetch "all players". Depending on what you are really trying to do, there are definitely much better ways of doing this.
     
    Last edited: Jul 21, 2023