- Home /
Loop through all objects with same tag?
How can I loop and then count all objects that share the same tag? Thanks.
Answer by Eric5h5 · Mar 02, 2011 at 06:39 PM
var objects = GameObject.FindGameObjectsWithTag("blah");
var objectCount = objects.Length;
foreach (var obj in objects) {
// whatever
}
Well, he wanted a count of all objects with a given tag, apparently.
Can someone translate this to C#? I am getting problems doing that.
@Johan: That is C#. You requested C#, so that's what I posted, and it's working code.
@Johan: no, it is not Javascript. Javascript does not have the foreach keyword, and could use objects.length ins$$anonymous$$d of objects.Length. I guarantee 100% that's working and valid C#, since like most code I post, I actually test it to make sure I'm not writing nonsense.
It's not c# c uses int a not var keyword to instantiate variables.
It is in fact c# - see https://msdn.microsoft.com/en-us/library/bb383973.aspx
var objectCount = objects.Length; //implicitly typed to int
int objectCount = objects.Length; //explicitly typed to int
Answer by FrHaYwOrKs · Apr 19, 2011 at 08:56 AM
While Eric5h5's answer is actually working for C#, I'm just posting the JS version, for all of you, lazy people! :)
var objects = GameObject.FindGameObjectsWithTag("blah");
var objectCount = objects.length;
for (var obj : GameObject in objects) {
// whatever
}
Eric5h5's answer is now JS in case anyone was like 'WHHAAAA?"