I’m working on a destructible environment and when a wall breaks 4 equal parts fall away.
In script I want to pass a variable to each of the 4 child instances.
I wouldn’t think this would work properly if the prefab of the 4 parts were in a group when the script with the variable is attached to each wall piece not the actual prefab.
I was looking at something like this example I found in the questions area.
Bullet zBullet = Instantiate(bullet, transform.position, Quaternion.identity) as Bullet;
zBullet.playerNum = playerNumber;
But I think this would just make the zBullet have the variable not any child of it.
Any way to pass a variable to a child of an Instantiated prefab?
thanks
If the four parts have the same script (let’s suppose it’s called ChildScript.cs) you can do something like this:
public GameObject wallPrefab; // wall prefab
...
// Instantiate the wall:
GameObject wall = Instantiate(wallPrefab, ...) as GameObject;
// for all children in wall...
foreach (Transform child in wall.transform){
// try to get the child script:
ChildScript script = child.GetComponent< ChildScript>();
if (script){ // if it has such script...
script.someVar = someValue; // set its variable
}
}
...
EDITED: I thought your code was in C# - there goes the JS version:
var wallPrefab: GameObject; // wall prefab
...
// Instantiate the wall:
var wall: GameObject = Instantiate(wallPrefab, ...);
// for all children in wall...
for (var child: Transform in wall.transform){
// try to get the child script:
var script: ChildScript = child.GetComponent(ChildScript);
if (script){ // if it has such script...
script.someVar = someValue; // set its variable
}
}
...