Search Unity

Count Tags

Discussion in 'Scripting' started by nmceri, Sep 26, 2005.

  1. nmceri

    nmceri

    Joined:
    Aug 4, 2005
    Posts:
    56
    Is there a way to count the number of objects with a particular tag?
    The closest i could find was FindGameObjectsWithTag which returns a list, but i wasn't able to use the Count with that. Are there other methods for doing this?

    Code (csharp):
    1. var tags = GameObject.FindGameObjectsWithTag ("test");
    2. tags = tags.Count;
     
  2. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    If Count doesn't work, you should be able to count the number of items with the Length property. (For some reason, the different list and array implementations in the .Net runtime library either define the length using Length or Count.... I need to find out which one always work or in which cases to use which one.)

    Code (csharp):
    1.  
    2. var numberOfItems =  GameObject.FindGameObjectsWithTag ("test").Length;
    3.  
    By the way. Even if Count works on the result from FindGameObjectsWithTag, your example would fail with a type error, since you are trying to assign an integer to a variable which is originally a GameObject list.
     
  3. nmceri

    nmceri

    Joined:
    Aug 4, 2005
    Posts:
    56
    Thanks for pointing that error out!
    From now on I'll just have to try both count and length and It'll work itself out.

    It does behave slightly funny. When a global variable is set using this method, the variable won't update after you've placed the script on an object, no matter how many new objects with that tag you've placed. Of course... removing the script and putting it back on will remedy this. It's like other global variables that way, so it wasn't too hard to figure out what was going on, but it did throw me off at first.
     
  4. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    That is because the assignment is just a default value for the variable. The real value comes from the value in the inspector.

    You can get around this if you declare the variable as private or if you initialise it in a separate line.