Friday, February 6, 2015

Using Unity Instantiate to create child objects

I'm building a tetris like board and was using Instantiate to create a group of tiles that were a move piece and when I moved the parent object, non of them moved.  It wasn't hard to fix, simply set the parent of the instantiated object.


            Transform ttmp = (Transform)Instantiate(goal_tile, goal_tile.position, goal_tile.rotation);
            tile.transform.position = new Vector2(
                (cellToCol(i) * tile_plain.rect.width) / tile_plain.pixelsPerUnit,
                (cellToRow(i) * tile_plain.rect.width) / tile_plain.pixelsPerUnit);
            ttmp.parent = transform;


Then in the update method, I can move the entire group of tiles like this



       Transform t2 = GetComponent();
       t2.position = new Vector3(t2.position.x + 0.005f, t2.position.y, t2.position.z);



In this case I'm getting the Transform associated with myself and adding a small amount to the x position. It doesn't do much because it just moves of the screen, but the game is getting closer bit by bit.