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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Objects not being spawned in at the correct locations

Discussion in 'Scripting' started by Wuffdoge, Feb 24, 2020.

  1. Wuffdoge

    Wuffdoge

    Joined:
    Dec 5, 2018
    Posts:
    3
    I have a thing that shoots 4 projectiles. 1 up, 1 down, 1 right, and 1 left. For some reason when I spawn in all 4 at once, it mixes up the locations and for example, the projectile that is supposed to go down is added at the left side of the object, the one that is supposed to go left is on the right, etc. However, when I add one in instead of all four, that one projectile is added in at the correct location and goes in its correct direction.

    Here is the code that spawns in the projectiles. If you need any other code let me know.

    Code (CSharp):
    1. Vector2 above = new Vector2(transform.position.x, transform.position.y + 1f);
    2.         Vector2 below = new Vector2(transform.position.x, transform.position.y - 1f);
    3.         Vector2 rightOf = new Vector2(transform.position.x + 1f, transform.position.y);
    4.         Vector2 leftOf = new Vector2(transform.position.x - 1f, transform.position.y);
    5.  
    6.         Instantiate(shot1, above, transform.rotation);
    7.         shot1.tag = "shot up";
    8.  
    9.         Instantiate(shot2, below, transform.rotation);
    10.         shot2.tag = "shot down";
    11.  
    12.         Instantiate(shot3, rightOf, transform.rotation);
    13.         shot3.tag = "shot right";
    14.  
    15.         Instantiate(shot4, leftOf, transform.rotation);
    16.         shot4.tag = "shot left";
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,748
    The first thing that jumps out at me, assuming you're using the tags to determine which one is where, is that you're not changing the tags of the objects you're generating. "shot1" still refers to the prefab, even after you spawn a copy of it.

    Try this:
    Code (csharp):
    1.  
    2. GameObject spawned1 = Instantiate<GameObject>(shot1, above, transform.rotation);
    3. spawned1.tag = "shot up";
     
  3. Wuffdoge

    Wuffdoge

    Joined:
    Dec 5, 2018
    Posts:
    3
    It worked thank you so much :)