Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question GameObject.FindGameObjectsWithTag() Returns null although there is an object with tag

Discussion in 'Scripting' started by ItsMe1423, Apr 1, 2024.

  1. ItsMe1423

    ItsMe1423

    Joined:
    Sep 23, 2020
    Posts:
    78
    [code = CSharp]GameObject specificMenu = null;
    GameObject[] Menus = GameObject.FindGameObjectsWithTag("PlayerMenu");
    Debug.Log(Menus.Length);
    [/code]

    it writes 0 as the menus.Length

    This is the Object
    upload_2024-4-1_19-27-16.png

    Help would be much appreciated, if more info is required please ask for it
     
    Last edited: Apr 1, 2024
  2. termway

    termway

    Joined:
    Jul 5, 2012
    Posts:
    90
    Posted in wrong forum section (see Scripting).

    According to the FindGameObjectsWithTag documentation, the object must be active in order to be found:
    • Returns an array of active GameObjects tagged tag. Returns empty array if no GameObject was found.
    There are several solutions for you:
    • Use direct reference to your menus
    • For UI you can let the game objects active and only disable the canvas
    • Use GetComponentInChildren on the parent game object with the includeInactive parameter set at true
    • ...
     
  3. ItsMe1423

    ItsMe1423

    Joined:
    Sep 23, 2020
    Posts:
    78
    Thank I will try that
    I was unsure of where to post it I didn't see scripting thanks for pointing it out for me :)
     
  4. ItsMe1423

    ItsMe1423

    Joined:
    Sep 23, 2020
    Posts:
    78
    It seems that the GetComponentsInChildren only works on active items aswell
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,586
    Kurt-Dekker likes this.
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    39,020
    Almost everything in Unity ONLY ever considers active GameObjects.

    It's all laid out in the docs along with any special considerations, such as the special "will wake stuff up" behaviour of the collision methods.

    NOTE: read it carefully, the words really have meaning. There's a massive difference between inactive GameObjects and disabled Components.

    You really will save time by starting from the official documentation on this stuff.