- Home /
The question is answered, right answer was accepted
How use local position of prefab for my instantiate ?
Hi, i make a room generator. My room " piece " are in the right position, fixed by my first script :
private var leveltaille = 75;
private var nbpiece : int;
public var piece: Transform;
function Start () {
nbpiece = Random.Range(6,12);
for (var i: int = 0; i < nbpiece; i++) {
Instantiate(piece, new Vector3(Random.Range(-leveltaille, leveltaille), 0, Random.Range(-leveltaille, leveltaille)), Quaternion.identity);
}
}
Then my second script instanciated many block in a grid and put them as child of my prefab piece :
private var PieceLargeurTaille : int;
private var PieceLongueurTaille : int;
var piece : GameObject;
var block : GameObject;
var spacing = 2.0;
function Start () {
PieceLargeurTaille = Random.Range(4,8);
PieceLongueurTaille = Random.Range(5,8);
for (var y = 0; y < PieceLargeurTaille; y++) {
for (var x=0;x<PieceLongueurTaille;x++) {
var pos = Vector3 (x, 0, y) * spacing;
var mapiece = Instantiate(block, pos, Quaternion.identity) as GameObject;
mapiece.transform.parent = transform;
}
}
}
But something wrong for me, the block are positioned with world not "piece" prefab. How can i do this ? Thanks for help.
I think i need to make 3 var, for x y and z and find a way to have the position of my gameobject inside.
Then add the number in the vector 3 position on my block.
I continue to search...
Answer by Bunny83 · Jul 18, 2017 at 03:09 AM
To positioning an instantiated object in local coordinates you can do the following:
Either
var mapiece = Instantiate(block, pos, Quaternion.identity) as GameObject;
mapiece.transform.SetParent(transform, false); // note the "false"
or
var mapiece = Instantiate(block) as GameObject;
mapiece.transform.parent = transform;
mapiece.transform.localPosition = pos;
Year thanks you so mutch ! i understand the 2 answer, very interesting.
Follow this Question
Related Questions
Changing localPosition gives no error, but doesnt change prefab localPosition 0 Answers
GameObject position and localPosition not changing in hiearchy, only in script. 0 Answers
Instantiate Object At Local Position 2 Answers
Instantiated Object being auto-deleted 0 Answers
Issue Instantiating prefab in C# 0 Answers