I am using System.Collection.generic to count all the objects currently created, however at a inconsistent time mostly arround 7/12 objects created list.count gives back odd numbers like 27 or 35 as example.
I think this has to do with the update method not being fast enough at loading the objects. But I am quite unsure.
PS. Also as you might have noticed, the code isn’t very optimalized any tips are very welcome.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnemySpawner : MonoBehaviour {
private Material color;
private int spawnedCreatures = 0;
public int spawnCap = 5;
public float spawnClosest = 3, spawnFarest = 15; // min and max spawn distance of each enemy
private GameObject player;
private List<GameObject> units = new List<GameObject>();
private float playerPosX, playerPosZ;
/*
* set the material of the cube,
* get the position of the player
*/
void Start () {
color = (Material)Resources.Load ("goblin");
// we might eror on here if unity cant find the tag player but it should be fine because we set a tag in the player script
player = GameObject.FindGameObjectWithTag ("Player");
playerPosX = player.transform.position.x;
playerPosZ = player.transform.position.z;
}
/*
* loop to spawn enemies
* get a new position for a enemy
* check if the position of each enemy and the player is far away enough
* Set a new game object, insert a cuber and set the material for the cube.
* Set the position and add a tag Enemy
* Last the script Enemy
*/
void Update () {
if (spawnedCreatures < spawnCap) {
Vector3 newPosition = new Vector3 (Random.Range(playerPosX - spawnFarest, playerPosX + spawnFarest), 1f , Random.Range(playerPosZ - spawnFarest, playerPosZ + spawnFarest));
GameObject emptyObject, cube;
// Set all units in a list
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag ("Enemy")) {
units.Add (enemy);
}
units.Add (player);
// check if the distance between all units is far away enough from echother.
// else we restart the loop
foreach (GameObject unit in units) {
if ((unit.transform.position - newPosition).magnitude < spawnClosest) {
return;
}
}
// set a new object
emptyObject = new GameObject ("Goblin");
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.parent = emptyObject.transform;
cube.GetComponent<MeshRenderer>().material = color;
emptyObject.transform.position = newPosition;
emptyObject.tag = "Enemy";
emptyObject.AddComponent<Enemy> ();
spawnedCreatures = units.Count - 1; // -1 because we dont want to count the player
Debug.Log(spawnedCreatures);
units.Clear(); // clear the list of unallowed positions for the enemies. we dont want double entries
}
}
}