Some problem with the changes made with the foreach loop

when i used the foreach loop in my code and run the game on a single enemy my enemy doest go to all the points of the array he just get to the 3rd point and destroy itself i want to make sure if the list start the counting of its components from 0 or 1 ???

this is the wave config code


public class WaveConfig : ScriptableObject
{
    [SerializeField] GameObject enemyPrefab  ;
    [SerializeField] GameObject pathPrefab;
    [SerializeField] float timeBetweenSpawns = 0.5f;
    [SerializeField] float spawnRandomFactor = 0.3f;
    [SerializeField] int numberOfEnemies = 5;
    [SerializeField] float movespeed = 3f; 


    public GameObject GetEnemyPrefab()
    {
        return enemyPrefab;
    }

    public List<Transform> GetWayPoints()
    {
        var waveWayPoints = new List<Transform>();
        foreach (Transform child in pathPrefab.transform)
        {
            waveWayPoints.Add(child);
        }
        return waveWayPoints;
    }

    public float GetTimeBetweenSpawns()
    {
        return timeBetweenSpawns;
    }
    
    public float GetSpawnsRandomFactor()
    {
        return spawnRandomFactor;
    }

    public float GetMoveSpeed()
    {
        return movespeed;
    }

    public int GetNumberOfEnemies()
    {
        return numberOfEnemies;
    }
}

this is the enemy pathing code

public class EnemyPathing : MonoBehaviour
{
    //game params
    [SerializeField] WaveConfig waveConfig;
    List<Transform> wayPoints ;
    [SerializeField] int wayPointIndex = 0 ;
    [SerializeField] float enemySpeed = 1f ;
    int listLength;

    //debug perpose 
    



    // Start is called before the first frame update
    void Start()
    {
        wayPoints = waveConfig.GetWayPoints();
       
        gameObject.transform.position = wayPoints[wayPointIndex].transform.position;
        
        listLength = wayPoints.Count -1;
    }

    // Update is called once per frame
    private void Update()
    {
        float distanceLeft = Vector2.Distance(gameObject.transform.position, wayPoints[wayPointIndex].transform.position);

        if (distanceLeft != 0)
        {
            gameObject.transform.position = Vector2.MoveTowards(gameObject.transform.position, wayPoints[wayPointIndex].transform.position, enemySpeed * Time.deltaTime);
        }
        else
        {
            wayPointIndex++;
        }
        if(wayPointIndex == listLength )
        {
            Destroy(gameObject);
        }
        
    }
}

i found the solution XD … when i writed waypoints.count to see how many way points are there
i wrote -1 …

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms