My method is adding new gameobjects in to the game... (Please help)

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);
    }

}

Going to be pretty honest here mate - this code is a complete mess. You’re doing some really, really weird things that don’t make a whole lot of sense.

The source of your issue is probably this:

  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);
 }

You’re calling the function, from inside the function, here:

      if(enemies().Count == null)

Are you sure you didn’t mean to use enemies_list there?

That’s just scratching the surface of issues I see but that’s where your stack overflow is coming from: You call the enemies() function, then inside that function you call enemies() which calls a new enemies() function which inside that function calls the enemies() function again… so on and so on infinitely.

GameObject closest_inside =new GameObject();

“create a new game object and assign it to the variable”…

GameObject closest_inside;

“create a variable of type GameObject”

you want the second one.

but you’re doing it the hard way trying to maintain two lists, one of gameobject and one of distances. You can have a single list of the enemies and sort them by their properties

i.e.

using System.Linq;

// class level variable to hold enemies
private List<GameObject> enemies;

// inititlise the enemies list when you need to


private GameObject GetClosestEnemy()
{
    enemies.Sort(
                    (unit1, unit2) =>
                    (transform.position - unit1.transform.position).sqrMagnitude.CompareTo(
                        (transform.position - unit2.transform.position).sqrMagnitude)
                    );
                    
    return enemies.First();
}
1 Like

Well, i tried some new things out, but i would like to get some help with it because this way of programming is completly new for me…

So it’s hard to understand because i never used this functions before (the functions with variables). So what should i change?

this look good men, wow hahah.

Could you explain what this exactly do, because i used another methode for this.

the sort method takes a delegate function

https://unity3d.com/learn/tutorials/modules/intermediate/scripting/delegates