Search Unity

Only 1 Tagged Object is added to the List

Discussion in 'Scripting' started by Andreas12345, Aug 19, 2019.

  1. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    526
    I try to add 2 tagged objects to the list
    Player and OtherPlayer
    But when i call the function always only TAG_1 is added to the List:(

    What i need to do, that both tagged objects are added to the list?

    Code (CSharp):
    1. private GameObject go;
    2.     private GameObject go2;
    3.  
    4.     public void AddRiders()
    5.     {
    6.  
    7.         GameObject[] tag;
    8.         GameObject[] tag_2;
    9.  
    10.  
    11.         tag = GameObject.FindGameObjectsWithTag("Player");
    12.         Debug.Log("Found TAG_1");
    13.         tag_2 = GameObject.FindGameObjectsWithTag("OtherPlayer");
    14.         Debug.Log("Found TAG_2");
    15.  
    16.  
    17.         for (int i = 0; i < tag.Length; i++)
    18.  
    19.         {
    20.             players.Add(tag[i].GetComponent<PlayerTicket>());
    21.             Debug.Log("Add TAG_1");
    22.         }
    23.  
    24.         for (int i = 0; i < tag_2.Length; i++)
    25.  
    26.         {
    27.             players.Add(tag_2[i].GetComponent<PlayerTicket>());
    28.             Debug.Log("Add TAG_2");
    29.         }
    30.  
    31.     }
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    The most likely problems I can think of are:

    A) Your code is throwing an exception and aborting before it finishes (check your console), or
    B) You don't have any objects with tag "OtherPlayer" in your scene

    Notice that your code is logging "Found TAG_2" whether it actually found any of that tag or not; that line will print even if it found zero of them. Consider logging the number of objects, e.g.

    Debug.LogFormat("Found {0} objects with TAG_2", tag_2.Length);
     
    Andreas12345 likes this.
  3. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    526
    That helped me to find out that i called the function for other player in the wrong part of my code.
    Thank you :)