- Home /
Instantiate as a Child of the Parent in for loop
Hello, everyone I'm trying this code
public GameObject group;
public GameObject spriteofobject;
void Start(){
int sekilKareSayi;
var rotation = transform.rotation = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);
for (sekilKareSayi = 1; sekilKareSayi == 1; sekilKareSayi++)
{
var position = transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, 0.0f);
var create = Instantiate(spriteofobject, position, rotation);
create.transform.parent = group.transform;
for (sekilKareSayi = 1; sekilKareSayi <= 3; sekilKareSayi++)
{
var position1 = transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y - 0.320f, 0.0f);
var create1 = Instantiate(spriteofobject, position1, rotation);
create1.transform.parent = group.transform;
}
}
}
but it's not creating 'create' and 'create1' as a child of parent 'group' object
Hmmm... that looks like it should work... Do those objects use RectTransforms ins$$anonymous$$d of Transforms?
Is the group variable null in the inspector?
Answer by cstooch · Jul 09, 2017 at 05:12 PM
Is this for troubleshooting??
for (sekilKareSayi = 1; sekilKareSayi == 1; sekilKareSayi++)
Why are you using a For loop to do something that can only iterate once? On top of that, you're using the same variable name in your nested loop, which can cause unexpected results if you haven't really thought out what will happen with this variable. Anyways, that's not the issue here, I wouldn't think, so...
Your reference "group"... did you set this to an instance of group? Or a prefab? Ensure it's an instance. I think you'd get an error if it was a prefab though. Also, another way of doing this... you can actually instantiate with a parent specified:
var create = Instantiate(spriteofobject, group.transform);
Maybe that will give you better results, although I can't see why the way you did it would not work. When you look in the hierarchy, where does your object show parented to?
I solved the problem. It was creating random thing. I forgot to add code block sorry.
Your answer