Search Unity

Foreach works twice

Discussion in 'Scripting' started by b4gieta, Aug 13, 2019.

  1. b4gieta

    b4gieta

    Joined:
    Jul 17, 2018
    Posts:
    97
    Hi
    I want to instantiate all eniemes in array of game objects, but they are instantiated twice. Why does it happen?
    Code (CSharp):
    1. if (!spawned)
    2.         {
    3.             foreach (GameObject enemy in enemiesToKill)
    4.             {
    5.                 Instantiate(enemy, enemy.transform.position, enemy.transform.rotation);
    6.                 spawned = true;
    7.             }
    8.         }
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,780
    @Evoroso do you run your script in Update, or at initialization?
    You maybe simply have two scripts attached to GameObjects.

    In your Project tab in Unity, right click on the script and click Find References in Scene

    upload_2019-8-13_12-46-38.png
     
    NoctisShadowzel likes this.
  3. b4gieta

    b4gieta

    Joined:
    Jul 17, 2018
    Posts:
    97
    Thanks a lot! There was a second game object with the same script!