Why cant my FindGameObjectsWithTag function find any objects?

I have 3 buttons placed in my scene and I want to find out how many there are in the scene by using FindGameObjectsWithTag(“Button”) and buttons.Length. But for some reason buttons.Length keeps giving me the value zero even though there are 3 buttons in my scene with the tag “Button”.

Here is my code:

using UnityEngine;
using System.Collections;

public class ButtonChecker : MonoBehaviour {
	public int amountofButtons;
	public GameObject FirstButton;
	public ButtonPress ButtonPresser;
	public GameObject[] buttons;

	void Start() {
		ButtonPresser = FirstButton.GetComponent<ButtonPress> ();

		if (buttons == null) {
			buttons = GameObject.FindGameObjectsWithTag("Button");
		}

		amountofButtons = buttons.Length;
	}
	
	// Update is called once per frame
	void Update () {
		Debug.Log (buttons.Length);
		if (ButtonPresser.activeButtons == amountofButtons) {
			//Debug.Log ("All Buttons are pressed!!");
		} 

		else {
			//Debug.Log("All not Pressed");
		}
	}
}

Hey

Not sure which, but this will almost certainly be 1 of these few problems:

  • The buttons are ‘disabled’, in which case the Find function won’t pick them up
  • The case is wrong in the tag (i.e. they’re called button, not Button - easy mistake to make!)
  • You’re confusing ‘layer’ with ‘tag’
  • As it is a public (serialised) property, ‘buttons’ is never null, so you never actually do the search - it starts off as a 0 length array and stays that way. Try doing the search regardless of whether it starts null, or even do it every frame to see if that fixes it.

Could be wrong, but check those out first :slight_smile:

-Chris

Hi,
are you sure you have the objects with “button” Tag and not with “Button” Layer?