Search Unity

Question Spawning two units instead of one

Discussion in 'Code Editors & IDEs' started by Kheprii, Sep 23, 2022.

  1. Kheprii

    Kheprii

    Joined:
    Jan 19, 2022
    Posts:
    1
    Hello!
    I am using Lambda to try to spawn units onto a grid, however, when I attempt to spawn a unit, it spawns two units instead of just one. I have four different heroes that I'm trying to spawn, but for now I just have the code written for one hero.
    Here's the code that's relevant to this.

    in UnitManager script:

    public void SpawnKids()
    {


    var kidPrefab = GetUnit<BaseKid>(team.kid, kidNumber.kid1);
    var spawnedKid = Instantiate(kidPrefab);
    var randomSpawnTile = GridManager.Instance.GetKidSpawnTile();
    randomSpawnTile.setUnit(spawnedKid);

    }
    private T GetUnit<T>(team Team, kidNumber Number) where T : BaseUnit
    {
    return (T)units.Where(u => u.team == Team).Where(n => n.kidNumber == Number).OrderBy(o => Random.value).First().unitPrefab;
    }

    Note that Visual Studio states that this script only has one reference.

    in GridManager script:


    public _Tile GetKidSpawnTile()
    {
    return tiles.Where(t => t.Key.y > height / 2 && t.Value.Spawnable).OrderBy(t => Random.value).First().Value;
    }

    In _Tile Script:

    public void setUnit(BaseUnit unit)
    {
    if(unit.occupiedTile != null)
    {
    unit.occupiedTile.occupiedUnit = null;

    }
    unit.transform.position = transform.position;
    occupiedUnit = unit;
    unit.occupiedTile = this;
    }

    In GameManager script:


    public void ChangeState(GameState newState)
    {
    switch (newState)
    {
    case GameState.GenerateGrid:
    GridManager.Instance.GenerateGrid();
    break;
    case GameState.SpawnKids:
    UnitManager.Instance.SpawnKids();
    break;
    case GameState.SpawnDaddy:
    break;
    case GameState.Player1:
    break;
    case GameState.Player2:
    break;
    case GameState.Player3:
    break;
    case GameState.Player4:
    break;
    case GameState.DaddyTurn:
    break;
    default:
    throw new ArgumentOutOfRangeException(nameof(newState), newState, null);
    }

    Note that this is only called twice, once at the start of the game, and once in the GenerateGrid script to change the state to SpawnKids.

    Please help, I don't understand what I'm doing wrong.