Get number from all tagged objects

``Ok, I have an enemy spawning script here. How it works is there is a spawn controller object that tells each spawner object what round it is and other information that needs to be the same between all of the spawner objects. Here is the script on the spawn controller:

var Spawn : boolean = true;
var Round : int = 1;
var Enemies;
var AllDead : boolean;
var Spawners;
var EnemiesToSpawn : int;
var EnemiesSpawned : int;
var EnemiesLeft : int;
function Update()
{
	Spawners = GameObject.FindGameObjectsWithTag("Spawner");
	EnemiesLeft = Spawners.GetComponent(Spawner).EnemiesSpawned;
	Enemies = GameObject.FindGameObjectsWithTag("Enemy");
	if(Enemies.lenth == 0){
		AllDead = true;
	}
	
	if(Round == 1)
	{
		EnemiesToSpawn = 20;
	}
	
	if(Round == 2)
	{
		EnemiesToSpawn = 30;
	}
	
	if(Round == 3)
	{
		EnemiesToSpawn = 40;
	}
	
	if(Round == 4)
	{
		EnemiesToSpawn = 50;
	}
	
	if(Round == 5)
	{
		EnemiesToSpawn = 60;
	}
	if(Round == 6)
	{
		EnemiesToSpawn = 70;
	}
}

and here is the script on each individual spawner:

var Enemy : Transform;
var SpawnController : Transform;
var SpawnTrue : boolean;
var WaitTime : int;
var MinWait : int = 1;
var MaxWait : int = 10;
var Round : int;
var EnemiesSpawned : int;
var EnemiesLeft : int;
var EnemiesToSpawn : int;
var RoundDone : boolean = false;
function Start()
{
	Round = SpawnController.GetComponent(SpawnTimer).Round;
	SpawnTrue = SpawnController.GetComponent(SpawnTimer).Spawn;
	WaitTime = Random.Range(MinWait,MaxWait);

}

function Spawn()
    { 
      if(RoundDone){
      SpawnTrue = false;
      	yield WaitForSeconds(15);
        Instantiate(Enemy, transform.position, transform.rotation);
        EnemiesSpawned ++;
      	EnemiesLeft --; 
       	ResetWait();
       	SpawnTrue = true;
     }
     
    if(RoundDone == false) 
     {
        SpawnTrue = false;  
        yield WaitForSeconds(WaitTime);
        Instantiate(Enemy, transform.position, transform.rotation);
        EnemiesSpawned ++;
        EnemiesLeft --; 
        ResetWait();
        SpawnTrue = true;
      }  
}



function Update()
{
	EnemiesLeft = EnemiesToSpawn - EnemiesSpawned;
	EnemiesToSpawn = SpawnController.GetComponent(SpawnTimer).EnemiesToSpawn;
	var AllDead = SpawnController.GetComponent(SpawnTimer).AllDead;
	Round = SpawnController.GetComponent(SpawnTimer).Round;
	if(EnemiesSpawned == EnemiesToSpawn)
	{
		if(AllDead)
		RoundDone = true;
		print("Next Round");
		EnemiesSpawned = 0;
		EnemiesLeft = EnemiesToSpawn;
		AddToRound();
	}
	
		if(EnemiesSpawned < EnemiesToSpawn)
	{
		RoundDone = false;
	}
	
		if(EnemiesSpawned > EnemiesToSpawn)
	{
		RoundDone = false;
	}
	
	if(SpawnTrue)
	{
		Spawn();
	}
	
	SetWait();
}
function ResetWait()
{
	WaitTime = Random.Range(MinWait, MaxWait);
}


function SetWait()
{
	if(Round == 1)
	{
		MinWait = 1;
		MaxWait = 10;
	}
	
	if(Round == 2)
	{
		MinWait = 2;
		MaxWait = 9;
	}
}


function AddToRound(){
	Round ++;
}

My problem here is in this line:

	Spawners = GameObject.FindGameObjectsWithTag("Spawner");
	EnemiesLeft = Spawners.GetComponent(Spawner).EnemiesSpawned;

I need to find the variable EnemiesSpawned from each of my spawners and add them together to get one number. How do you find a variable from each of the objects without having to list each one?

When I try that I get this error:

MissingMethodException: Method not found: 'UnityEngine.GameObject[].GetComponent'.
Boo.Lang.Runtime.DynamicDispatching.MethodDispatcherFactory.ProduceExtensionDispatcher ()
Boo.Lang.Runtime.DynamicDispatching.MethodDispatcherFactory.Create ()
Boo.Lang.Runtime.RuntimeServices.DoCreateMethodDispatcher (System.Object target, System.Type targetType, System.String name, System.Object[] args)
Boo.Lang.Runtime.RuntimeServices.CreateMethodDispatcher (System.Object target, System.String name, System.Object[] args)
Boo.Lang.Runtime.RuntimeServices+<Invoke>c__AnonStorey12.<>m__6 ()
Boo.Lang.Runtime.DynamicDispatching.DispatcherCache.Get (Boo.Lang.Runtime.DynamicDispatching.DispatcherKey key, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory)
Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.String cacheKeyName, System.Type[] cacheKeyTypes, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory)
Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.Object[] args, System.String cacheKeyName, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory)
Boo.Lang.Runtime.RuntimeServices.Invoke (System.Object target, System.String name, System.Object[] args)
SpawnTimer.Update () (at Assets/SpawnTimer.js:12)

Anyone?

Find…Objects returns an array, arrays don’t have member functions. You have to iterate.

for ( var spawner in GameObject.FindGameObjectsWithTag("Spawner") ) {
  total += spawner.EnemiesSpawned;
}

It’s a very good idea to use UpperCase for functions and classes and lowerCase for variables, helps keep confusion to a minimum.

I tried that and I get a null reference exception. I checked and all the names are right and there are now errors as far as capital letters and such.

Are there any other reasons that this would give me a nullreference exception? I haven’t referenced anything that isn’t there, so I don’t see any logical reason I should be getting this error.

You might try FindObjectsOfType(Spawner) instead, you could have a tagged object that doesn’t have an actual Spawner.

NullRef pops up sometimes if you try to access a nonexistent member of an (even strongly-typed!) object. Kinda irritating, not sure why the compiler sometimes fails to catch that sort of thing.

Yes, I have tried that but I get the same problem. This is turning out to be way harder than it should be.

What’s the current block of code that’s giving the issue?

This is the section that the error points to:

function Update()
{
	
	for ( var spawner in GameObject.FindGameObjectsWithTag("Spawner") ) {

  EnemiesStillSpawning += spawner.EnemiesSpawned;

}

or more specifically:

EnemiesStillSpawning += spawner.EnemiesSpawned;

Anybody?

your scripts are not my favorite to read but I believe your trying to accomplish something like a wave spawner so I’ll show you how I accomplished it and then you can go from there… hope it helps

BTW This is C#

/// <summary>
/// Game manager.
/// Created by, Daniel Brookshaw[KingCharizard] - Copyright 2012
/// </summary>
using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
	public static GameManager Instance;
	public GameState state;
	
	public GameObject player;
	public GameObject enemy;
	public int enemyCount;
	private int spawnCount = 0;
	public int waveCount = 0;
	public int maxSpawnCount = 5;
	private bool waveCompleted = false;
	private float waveDelay = 10.0f;
	private float range = 10f;
	
	//Creates an instance in the awake Function
	void Awake(){
    	Instance = this;
	}
	
	// Use this for initialization
	void Start () {
		enemyCount = maxSpawnCount;
		SpawnEnemies();
		state = GameState.Start;
		
		if(state == GameState.Start){
			state = GameState.Playing;
		}
		
	}
	
	// Update is called once per frame
	void Update () {
		SpawnWaveManager();
		
	}
	
	void SpawnWaveManager(){
		if(enemyCount == 0){
			state = GameState.WaveComplete;
			if(waveDelay == 10.0f){
				audio.Play();
			}
			waveDelay -= Time.deltaTime;
		}
			if(waveDelay < 0.0f){
				waveCount++;
				waveCompleted = true;
				waveDelay = 0;	
			}
		
		if(waveCompleted){
			EnemyWaves();
		}
		
	}
	
	
	void SpawnEnemies(){
		if(spawnCount < maxSpawnCount){
				while(spawnCount < maxSpawnCount){
				 Vector3 spawnPosition = new Vector3(Random.Range(-30f, 30f), 1.2f, Random.Range(38f, -38f));
				  if(Vector3.Distance(spawnPosition, player.transform.position) > range){
						Instantiate(enemy, spawnPosition, Quaternion.identity);
						spawnCount++;
				}
					
					
			}
		}
	}
	
	
		void EnemyWaves(){
		switch(waveCount){
			case(1):
				maxSpawnCount = 10;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				state = GameState.Start;
				break;
			case(2):
				maxSpawnCount = 15;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				state = GameState.Start;
				break;
			case(3):
				maxSpawnCount = 20;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				state = GameState.Start;
				break;
			case(4):
				maxSpawnCount = 25;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				break;
			case(5):
				maxSpawnCount = 30;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				break;
			case(6):
				maxSpawnCount = 35;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				break;
			case(7):
				maxSpawnCount = 40;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				break;
			case(8):
				maxSpawnCount = 45;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				break;
			case(9):
				maxSpawnCount = 50;
				waveCompleted = false;
				spawnCount = 0;
				enemyCount = maxSpawnCount;
				SpawnEnemies();
				waveDelay = 10.0f;
				break;
				}
		
	}
	
	
	void OnGUI(){
		if(state == GameState.WaveComplete){
		GUI.Label(new Rect(50,100, 200,200), "Next wave in: " + waveDelay);
		}	
	}
}

public enum GameState {
		
	Start,
	Playing,
	WaveComplete,
	Destroyed
	
}

Thanks! I will try it and study it.

I never had any training. I taught myself through trial and error. You aren’t the first person to say that. I just don’t know all the ways you SHOULD do it, just the way I know how.

Thanks again

FindGameObjectsWithTag returns a GameObject, not a Spawner. You used this earlier:

Spawners.GetComponent(Spawner).EnemiesSpawned;

Which means that Spawner is a component. So in your foreach, you’re getting objects and objects don’t have the EnemiesSpawned field.

I self taught aswell. My scripts aren’t the most efficient but they get the job done… as MadjackMcMad just said I believe this could be the case as it makes sense but again I am not certain. It still it doesn’t fix your problem…

My script wont fix your problem it was made for a game I was(am) developing but it will show you a different method you can use to spawn enemies.

Em, Spawner is the name of the script.

anybody?

Try using a specific type:

var spawner : Spawner in list