Hi all,
I just figured out a bug, but I really don’t understand how/why it works the way it does. In the WaveConfig script of the Laser Defender course, I have the GetWayPoints method that gets the waypoints of my path. In the following buggy code, the waypoints list variable is declared as a global variable. What happened was that every time I ran my game, the waypoints were added to the list, i.e. the list went from a count of 0 to a count of 3 (expected). However, when I stopped my program and ran it again, it added another 3 to make a total count of 6 (not expected). Then another 3, then another. By the time I figured out what it was doing (I realized my enemies weren’t destroying as expected), I had over 1000 items in the list. My understanding is that it was somehow holding the contents of the list in memory in between runs. Is that correct? If so, then why?
private List<Transform> _waveWayPoints;
public List<Transform> GetWayPoints()
{
foreach (Transform child in _pathPrefab.transform)
{
_waveWayPoints.Add(child);
}
Debug.Log("WaveWayPoints List has this many items: " + _waveWayPoints.Count);
return _waveWayPoints;
}
Here is the code that now works as expected. Here I got rid of the global variable and instead declared and initialized the list as a local variable within the method. Again, I’m not sure why this works, other than the fact that local variables have restricted access. If anyone could explain this to me, I’d really appreciate it :D. Thanks!
public List<Transform> GetWayPoints()
{
List<Transform> _waveWayPoints = new List<Transform>();
foreach (Transform child in _pathPrefab.transform)
{
_waveWayPoints.Add(child);
}
Debug.Log("WaveWayPoints List has this many items: " + _waveWayPoints.Count);
return _waveWayPoints;
}