- Home /
How to check if there are game objects with the same tag on screen?
I am trying to check if there are no more 'gems' left on the scene and if it's true, opening the exit portal. I tried doing this by using: if (GameObject.FindGameObjectsWithTag("Gem").Length == 0). I have no errors, but when the player picks up all the gems and goes to the portal, nothing happens. I also tried using if (GameObject.FindGameObjectsWithTag("Gem").Length != 0) with an else statement, but this didn't work as well. I have no idea what could be causing this issue.
Thanks.
Answer by logicandchaos · Nov 12, 2021 at 12:03 PM
you should debug it like
Debug.Log(GameObject.FindGameObjectsWithTag("Gem").Length);
Then you will know if you are collecting all the gems or if there is a problem with your portal.
Also a better way to do it maybe to keep track of the objects yourself with a counter. Their are a few ways to do this.. it depends on the gameObjects, if you just want ot go by tags you can make an int numberOfGems = GameObject.FindGameObjectsWithTag("Gem").Length;
Or if all your gems have the same script on them you can use a static int for them to keep track of themselves.
class Gem : MonoBeahviour
{
static in numberOfGems;
OnEnable(){
numberOfGems++;
}
OnDisable(){
numberOfGems--;
}
}
Then you can access that variable anywhere with Gems.numberOfGems, and go if(Gem.numberOfGems==0) etc..
Answer by unity_hosein · Nov 13, 2021 at 04:09 AM
if you are using visual studio use brack point to check what's wrong
Answer by flubber767 · Nov 13, 2021 at 06:34 AM
Thank you for answering. I ended up using a "count" variable and and putting the component on another object instead of the gem. In short, it works.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
setActive on object in separate scene 2 Answers
How can I count the number of instances of a tagged prefab? 1 Answer