- Home /
Instantantiate relative to parents position
Hi all,
Newbie here. I have a Room Object with my Room_Generation C# Script attached. When the Game started it randomly generates the room size and fills it with 4x4 tiles.
Problem being that it instantiates the tiles at Global 0,0,0 rather than the Room object 0,0,0. I can only manage to make the Tiles a parent of the Room Object after the instaniate. Any Ideas?
using UnityEngine;
using System.Collections;
public class Room_Generation : MonoBehaviour {
public GameObject Floor;
void Start () {
float fSpacing = 4.0f;
int iRoomWidth = Random.Range(0,4);
int iRoomLength = Random.Range(0,4);
for(int z = 0; z <= iRoomWidth; z++){
for(int x = 0; x <= iRoomLength; x++){
GameObject gFloor = Instantiate(Floor,new Vector3(x,0,z) * fSpacing,Quaternion.Euler(-90,0,0)) as GameObject;
gFloor.transform.parent = transform;
gFloor.name = "Floor_" + z + x ;
}
}
}
}
Thanks, got this fixed.
using UnityEngine;
using System.Collections;
public class Room_Generation : MonoBehaviour {
public GameObject Floor;
// Use this for initialization
void Start () {
float fSpacing = 4.0f;
int iRoomWidth = Random.Range(0,4);
int iRoomLength = Random.Range(0,4);
for(int z = 0; z <= iRoomWidth; z++){
for(int x = 0; x <= iRoomLength; x++){
GameObject gFloor = Instantiate(Floor) as GameObject;
gFloor.transform.parent = transform;
gFloor.transform.localPosition = new Vector3(x,0,z) * fSpacing;
gFloor.transform.rotation = Quaternion.Euler(-90,0,0);
gFloor.name = "Floor_" + z + x ;
}
}
}
}
Answer by robertbu · Nov 25, 2013 at 06:42 AM
Set the position and rotation after the instantiate and use local coordinates:
GameObject gFloor = Instantiate(Floor);
gFloor.transform.parent = transform;
gFloor.transform.localPosition = new Vector3(x,0,z) * fSpacing;
gFloor.transform.rotation = Quaternion.Euler(-90,0,0);
gFloor.name = "Floor_" + z + x ;
Thank you, Updated the working script above, you left out the "gFloor.Transform.rotation".
Your answer
Follow this Question
Related Questions
AddComponent() causes a "trying to create a MonoBehaviour using the 'new' keyword" warning 2 Answers
Camera follow script not following player? 1 Answer
How do i Instantiate a prefab with specific assests included 3 Answers
How to create a Graph in Unity 1 Answer
instantiated object not moving with parent transform. 0 Answers