Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

List of GameObjects empty even though i've added items

Discussion in 'Scripting' started by Boxprintz, Nov 24, 2020.

  1. Boxprintz

    Boxprintz

    Joined:
    Dec 17, 2019
    Posts:
    8
    Coding a 3d tower defense game, having problems accessing the enemies list in WaveScript from the FisherScript (The towers are fishers fishing fishes). I accualy have no clue what's going on, any help would be appreciated. I don't mind if you point out other problems either. Sorry for the mess and thank you.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEditor;
    4. using UnityEngine;
    5.  
    6. public class TowerDefenseScript : MonoBehaviour
    7. {
    8.     private List<GameObject> waves;
    9.     public List<GameObject> Waves { get => waves; }
    10.  
    11.     private int currentWave;
    12.     public int CurrentWave { get => currentWave; set => currentWave = value; }
    13.  
    14.     private bool waveOngoing;
    15.     public bool WaveOngoing { /* get => waveOngoing; */ set => waveOngoing = value; }
    16.  
    17.     [SerializeField]
    18.     private GameObject wavePrefab;
    19.  
    20.     // Start is called before the first frame update
    21.     private void Start()
    22.     {
    23.         waves = new List<GameObject>();
    24.         currentWave = 0;
    25.         StartCoroutine(wavePrefab.GetComponent<WaveScript>().CreateWave(currentWave, 10, 1, 5, 1));
    26.        
    27.  
    28.         //start times (s) for the waves
    29.         Waves[0].GetComponent<WaveScript>().PrepTime = 5;
    30.     }
    31.  
    32.     // Update is called once per frame
    33.     private void Update()
    34.     {
    35.  
    36.     }
    37. }
    38.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEditor;
    4. using UnityEngine;
    5. using System.Diagnostics;
    6. using Debug = UnityEngine.Debug;
    7.  
    8. public class WaveScript : MonoBehaviour
    9. {
    10.     [SerializeField]
    11.     private List<GameObject> enemyPrefabs;
    12.  
    13.     private int enemyCount;         // Number of enemies
    14.     private float scaleFactor;      // Scale all enemy stats by a factor
    15.     private int waveIndex;          // wave X since start of game
    16.     private float spawnInterval;    // time between each spawn of an enemy
    17.  
    18.     private int prepTime;           // Time (in seconds) to prepare before wave starts
    19.     public int PrepTime { get => prepTime; set => prepTime = value; }
    20.  
    21.     private List<GameObject> enemies;
    22.  
    23.     private void Awake()
    24.     {
    25.         enemies = new List<GameObject>();
    26.     }
    27.  
    28.     public IEnumerator CreateWave(int waveIndex, int enemyCount, float scaleFactor, int prepTime, float spawnInterval)
    29.     {
    30.         GameObject wave = Instantiate(gameObject, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
    31.         wave.transform.parent = GameObject.Find("WaveSpawnPoint").transform;
    32.         wave.transform.position = wave.transform.parent.position;
    33.         GameObject.Find("TowerDefense").GetComponent<TowerDefenseScript>().Waves.Add(wave);
    34.  
    35.         this.enemyCount = enemyCount;
    36.         this.scaleFactor = scaleFactor;
    37.         this.waveIndex = waveIndex;
    38.         this.spawnInterval = spawnInterval;
    39.  
    40.         PrepTime = prepTime;
    41.  
    42.         enemies = new List<GameObject>();
    43.  
    44.         GameObject.Find("TowerDefense").GetComponent<TowerDefenseScript>().WaveOngoing = true;  // waveOngoing = true, to prevent the next wave to start in TowerDefenseScript
    45.  
    46.         if (prepTime == 0)
    47.         {
    48.             yield return null;
    49.         }
    50.         else
    51.         {
    52.             yield return new WaitForSeconds(prepTime);
    53.         }
    54.  
    55.         GameObject.Find("TowerDefense").GetComponent<TowerDefenseScript>().CurrentWave += 1;
    56.  
    57.         Stopwatch timer = new Stopwatch();
    58.         timer.Start();
    59.  
    60.         for (int i = 0; i < enemyCount; i++)
    61.         {
    62.             Debug.Log("in coroutine: enemy count = " + enemies.Count);
    63.             float extraTime = timer.ElapsedMilliseconds/1000 - (i * spawnInterval);
    64.  
    65.             enemies.Add(enemyPrefabs[0].GetComponent<Enemy1>().createEnemy());
    66.             enemies[i].GetComponent<Enemy1>().ScaleStats(scaleFactor);              //scale enemy stats, option to not pass arguments
    67.  
    68.             float speed = enemies[i].GetComponent<Enemy1>().Speed;
    69.             enemies[i].transform.Translate(Vector3.forward * speed * extraTime);    // to make the distance between the spawns consistent
    70.  
    71.             yield return new WaitForSeconds(spawnInterval);
    72.         }
    73.     }
    74.  
    75.     public List<GameObject> GetEnemies()
    76.     {
    77.         return enemies;
    78.     }
    79. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public abstract class FisherScript : MonoBehaviour
    6. {
    7.     private FisherSpawningStates currentState;
    8.  
    9.     [SerializeField]
    10.     private protected int price;
    11.     public int Price { get => price; }
    12.  
    13.     [SerializeField]
    14.     private protected float range;
    15.  
    16.     [SerializeField]
    17.     private protected float dmg;
    18.  
    19.     public GameObject CreateFisher(Vector3 position)
    20.     {
    21.         GameObject fisher = Instantiate(gameObject, position, Quaternion.identity) as GameObject;
    22.         fisher.transform.parent = GameObject.Find("Fishers").transform;
    23.         return fisher;
    24.     }
    25.  
    26.     protected void Awake()
    27.     {
    28.         currentState = FisherSpawningStates.DEPLOYING;
    29.     }
    30.  
    31.     // Update is called once per frame
    32.     protected void Update()
    33.     {
    34.         GetClosestEnemy();
    35.         /*Debug.DrawLine(gameObject.transform.position, GetClosestEnemy().transform.position, Color.blue);
    36.         Debug.DrawRay(gameObject.transform.position, (GetClosestEnemy().transform.position - gameObject.transform.position).normalized, Color.blue);*/
    37.     }
    38.  
    39.     private protected GameObject GetClosestEnemy() //(within range)
    40.     {
    41.         List<GameObject> waves = GameObject.Find("TowerDefense").GetComponent<TowerDefenseScript>().Waves;
    42.         GameObject target = null;
    43.  
    44.         Debug.Log("Wave Count = " + waves.Count);
    45.  
    46.         if (waves.Count > 0)
    47.         {
    48.             for (int i = 0; i < waves.Count; i++)
    49.             {
    50.                 List<GameObject> enemies = waves[i].GetComponent<WaveScript>().GetEnemies();
    51.  
    52.                 Debug.Log("enemy Count = " + enemies.Count);
    53.  
    54.                 if (enemies.Count > 0)
    55.                 {
    56.                     for (int j = 0; j < enemies.Count; j++)
    57.                     {
    58.                         Debug.Log(enemies[j].name);
    59.                         float distance = (enemies[j].transform.position - gameObject.transform.position).magnitude;
    60.  
    61.                         if (target == null)
    62.                         {
    63.                             if (distance < range)
    64.                             {
    65.                                 target = enemies[j];
    66.                             }
    67.                         }
    68.                         else
    69.                         {
    70.                             float targetDistance = (target.transform.position - gameObject.transform.position).magnitude;
    71.  
    72.                             if (distance < targetDistance)
    73.                             {
    74.                                 target = enemies[j];
    75.                             }
    76.                         }
    77.                     }
    78.                 }
    79.             }
    80.         }
    81.         return target;
    82.     }
    83.  
    84.     public FisherSpawningStates GetCurrentState()
    85.     {
    86.         return currentState;
    87.     }
    88.  
    89.     public void SetCurrentState(FisherSpawningStates state)
    90.     {
    91.         currentState = state;
    92.     }
    93. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,697
    There's a lot of code here. Would you mind pointing in the direction of which lines of code you're having trouble with? Where are you trying to access data that isn't working right?
     
  3. Boxprintz

    Boxprintz

    Joined:
    Dec 17, 2019
    Posts:
    8
    third script, line 50.
    which refers to function in script two line 75
     
  4. Boxprintz

    Boxprintz

    Joined:
    Dec 17, 2019
    Posts:
    8
    I'm thinking that a problem could be with me instantiating the GameObject in the "CreateWave" method in script two
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,697
    And what is happening there? Is there an error? Are you just not seeing the right behavior?
     
  6. Boxprintz

    Boxprintz

    Joined:
    Dec 17, 2019
    Posts:
    8
    Yes, so i'm adding enemies, which are just cubes moving in one direction in the coroutine "CreateWave", but when calling the GetEnemies method its empty
     
  7. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Add a debug.log immediately after the line where you populate the list, and immediately before the line where you try to access it.

    I suspect that your GetClosestEnemy function is being called before line 33 in WaveScript executes.