Search Unity

Resolved Why can I set the position of one prefab when I instantiate it but not another?

Discussion in 'Scripting' started by polypixeluk, Jul 23, 2020.

  1. polypixeluk

    polypixeluk

    Joined:
    Jul 18, 2020
    Posts:
    53
    I have 3 objects.
    PlatformManager
    Platform
    Tile

    My Tile prefab is just a sprite and a Box Collider2D
    My Platform prefab is generated from n tile prefabs. Eg. 3 tiles.
    PlatformManager spawns platforms on a timer as children and moves to the left.

    If I Instantiate a Tile prefab directly, I can set it's position to that of a GameObject parented to the PlatformManager named spawnPoint.

    Code (CSharp):
    1. public GameObject tile;
    2. public Transform spawnPoint;
    3.  
    4. void Start() {
    5. Instantiate(tile, spawnPoint.position, Quaternion.identity, gameObject.transform);
    6. }
    That works as expected. The tile prefab appears positioned at the spawnPoint object's position. But if I use the same approach with the Platform:

    Code (CSharp):
    1. public GameObject platform;
    2. public Transform spawnPoint;
    3.  
    4. void Start() {
    5. Instantiate(platform, spawnPoint.position, Quaternion.identity, gameObject.transform);
    6. }
    The Platform prefab instantiates at the world origin.

    This is the platform generation code:

    Code (CSharp):
    1. public class PlatformGenerator : MonoBehaviour
    2. {
    3.     public int platformSize; //in tiles
    4.     public GameObject tile;
    5.     public float tileOffset;
    6.     Transform currentOffset;
    7.     Transform myTrans;
    8.  
    9.     void Start()
    10.     {
    11.         for (int i =0; i < platformSize; i++)
    12.         {
    13.             Instantiate(tile, new Vector3(i * tileOffset, 0, 0), Quaternion.identity, gameObject.transform);
    14.         }
    15.        
    16.     }
    17. }
    18.  
    Any ideas?
     
  2. adehm

    adehm

    Joined:
    May 3, 2017
    Posts:
    369
    Because your platform will also Instantiate what it is made up of which does not use your platform origin?
    'new Vector3(i * tileOffset, 0, 0)'
    should maybe use platform as a starting point?
    new Vector3(transform.position + i * tileOffset, 0, 0)'
     
    polypixeluk likes this.
  3. polypixeluk

    polypixeluk

    Joined:
    Jul 18, 2020
    Posts:
    53
    That was it! Thanks bud.