Find the number of prefabs from other scripts?

So after taking the “Roll a Ball” tutorial, I was wondering if there is a way to get either:

  1. the number of children in a game object, or
  2. the number of times a prefab is used in the game,

in scripts that are used by other game objects. In the case of Roll a Ball, instead of giving the script an integer from the Unity work space, I would like to have the player controller script get the number of existing pickups, and use that number in triggering the win text.

Thanks!

For getting the number of time a Prefab is used, you got to 2 options:

A) Keep track of the prefabs when they are instantiated with a public static integer (int) value.

This is possible if your prefabs are instantiated through script. If they are already in the scene when you start it, you got to apply those “initial” prefabs into the account. So, if you got a scene with 1 prefab in the scene (the main player) and some some are spawned, then when the scene start, set the static int value to 1 and whenever a prefab is spawned, add 1 to that int. Whenever the scene change and the number of prefab is “reset”, change the static int back to the relevant amount.

B) Have an unique tag for the prefabs and search for it in the scene.
Then you uses a

int NumberOfPrefabs = GameObject.FindGameObjectsWithTag("Tag").Length;

This will return the number of the specific prefabs in the scene. It does requires you to manage your tags carefully though.