Hello, iam trying a new way of programming (with a lot of stack overflow as result). So i fixed the stack overflow but know is my script adding new gameobject’s to the game. I know why it happens, but don’t know how to prevent stack overflow if i remove that line…
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WhiteSoldierAI_1stEdition : MonoBehaviour {
//this are all the bool's
//this bool say's if the soldier is alive or not
private bool alive;
//this is if the game starts for the first time
private bool first_time_1;
//this are all the gameobject's
//this are all the components
//the navmeshagent component, this is for the pathfinding
public NavMeshAgent agent;
//this are al the int's
//this int is just testing if the closest works
public float closest_distance_test;
// Use this for initialization
void Start ()
{
//the soldier will alway's start alive in the game
alive = true;
//the game laucnhes for the first time
first_time_1 = true;
}
// Update is called once per frame
void Update ()
{
//this will be setup for the test
closest_distance_test = Vector3.Distance(transform.position, Closest ().transform.position);
}
//this list contains all the enemies in the current level
private List<GameObject> enemies()
{
//i will add a new enemies list
List<GameObject> enemies_list = new List<GameObject>();
//if there are no enemies added
if(enemies().Count == null)
{
//now will i add al the enemies in the list
enemies_list.AddRange(GameObject.FindGameObjectsWithTag("Black_Soldier"));
}
//the enemies list will be returned after adding all the enemies
return(enemies_list);
}
//this list contains all the distance's from the soldier to the enemy
private List<float> enemies_distances()
{
//i will add a new list
List<float> enemies_distances_list = new List<float>();
//now will i add al the float's
enemies_distances_list.AddRange(new float[enemies ().Count]);
//now will i open a loop
for(int i = 0; i<enemies_distances_list.Count;i++)
{
//now will i calculate the distance
enemies_distances_list[i] = Vector3.Distance(enemies ()[i].transform.position, transform.position);
}
//i will now return the list after all the distance's was calculated
return(enemies_distances_list);
}
//here will the closest enemy be calculated
private GameObject Closest()
{
//we make a variable for the closeset distance
float closest_distance = new float();
//a closest gameobject
GameObject closest_inside = new GameObject();
//first we need to setup a loop
for(int i = 0; i < enemies_distances().Count; i++)
{
//then we calculate the closest enemy
if(closest_distance == 0 || enemies_distances()[i] <= closest_distance)
{
//then we will set the closest_distance and the closest to the closest enemy and distance
closest_distance = enemies_distances()[i];
//then the closest will be set
closest_inside = enemies ()[i];
}
}
//this is just for returning
return(closest_inside);
}
}