Search Unity

Instantiated gameobject taking transform position from prefab instead of gameobject

Discussion in 'Scripting' started by jwillis10, Oct 3, 2018.

  1. jwillis10

    jwillis10

    Joined:
    Mar 6, 2018
    Posts:
    1
    Hi there, so I'm making a turret defense game and I'm having trouble getting the turret to instantiate in the correct position. I have an "Emplacement" the player can click on, a couple ui buttons pop up the player can click, and depending on the button a different tower spawns.

    Code (CSharp):
    1. public void spawnTurret(int type)
    2.     {
    3.         if(type == 1 && turret == null)
    4.         {
    5.             GameObject turretToBuild = BuildManager.BM.GetTurretToBuild(); //Returns turret gameobject
    6.             turret = (GameObject)Instantiate(turretToBuild, transform.position, transform.rotation);
    7.  
    8.             Destroy(turretSelector); //UI element
    9.             isActive = false;
    10.         }
    11.         else
    12.         {
    13.             Debug.Log("Type out of range or turret already there!");
    14.         }
    15.     }
    But the transform.position returns the transform.position of the prefab of emplacement (only when instantiating though; checking via debug it returns correct positions) so the turret spawns at (0,0,0) instead of at the emplacement position. I've also tried instantiating the turret as a child but I get the "Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption" error.

    I'm not sure what else to try or where to go from here. Any and all suggestions are welcome!

    Oh and I'm on 2018.2.3 btw
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Line 6 above takes the position of the GameObject that this script is running on and uses that as its position and rotation for instantiating the new turret. Is that reasonable? That would mean the GameObject this script is on will have to first be moved to the spawn location BEFORE the spawnTurret function is called.