|
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; 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
(comments are locked)
|
|
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
}
}
...
Doesn't seem to work for me. GameObject wall = Instantiate tells me I need a ; in the line, but using var wall = Instantiate works.
function OnCollisionEnter(collision : Collision)
{if(health < 0)
{
var temp:Quaternion = transform.rotation;
var wall = Instantiate(blox, transform.position, temp);
wall.health=100;
Destroy (gameObject);
}
}
the wall.health=100; is where I get the trouble of it crashing. I can remove that line and all works out ok. I can put anything there with "wall." and it seems to crash. a transform.rotation seems to not crash it, but a transform.scale does. I can't get my head around what the issue could be.
Aug 08 '12 at 02:42 PM
redteardrop
I need it in JS, that looks like C. Would you know how to convert it to js? Mainly the foreach section. I'm pretty sure I can do the rest.
Aug 11 '12 at 03:31 PM
redteardrop
I got it to work, but I don't think I am using a parent child relationship anymore. here's what I did: var oneBlox : GameObject;
Oct 04 '12 at 03:40 PM
redteardrop
(comments are locked)
|
