- Home /
placing children objects in different places
I'm making a script where the player can chop down trees with an axe and it's going pretty good so far. However I've hit a small obstacle now. At a certain point, I want to respawn the trees (multiple objects per tree) in the same spot they were at. However I can't seem to figure out how to give each object a unique position. I've got my tree prefab and I want to set up the tree exactly how that is. Right now I just check each child object and put it back at a certain position but obviously this is going to be the position for each object. Is there a better way or similar way that works to do this? Heres the code I'm using right now.
var treeDead : boolean = false;
var treeHealth : int = 5;
var logWorth : int = 1;
function Update() {
if(treeHealth <= 0) {
if(!treeDead) {
treeHealth = 0;
TreeRespawn();
}
}
}
function OnTriggerEnter(itemHit : Collider) {
if(!treeDead) {
if(itemHit.tag == "Axe") {
treeHealth -= 1;
}
if(itemHit.tag == "Chainsaw") {
if(treeHealth >= 5) {
treeHealth -= 5;
}
else {
treeHealth -= treeHealth;
}
}
if(itemHit.tag == "Big Chainsaw") {
if(treeHealth >= 10) {
treeHealth -= 10;
}
else {
treeHealth -= treeHealth;
}
}
}
}
function TreeRespawn() {
for(var child : Transform in transform) {
child.rigidbody.isKinematic = false;
}
treeDead = true;
yield WaitForSeconds(50);
for(var child : Transform in transform) {
child.localPosition = Vector3(0, 2.75, 0);
}
for(var child : Transform in transform) {
child.rigidbody.isKinematic = true;
}
treeDead = false;
}
The lines in question are 44 and 45 [for(var child : Transform in transform) { child.localPosition = Vector3(0, 2.75, 0); }] Which is obviously just setting each objects position to that.
Answer by TeddyDief · Apr 25, 2013 at 08:58 PM
You could store a List or array of localPositions, one for each child, in your Start() function. Then, when respawning your tree, do something like...
var transforms : Transform[]; // Array of all Transforms
var transformPositions : Vector3[]; // Array of all positions
var transformRotations : Quaternion[]; // Array of all rotations
// ... after your WaitForSeconds() in TreeRespawn
for (var i = 0; i < transforms.Length; i++)
{
transforms[i].rigidbody.isKinematic = true;
transforms[i].localPosition = transformPositions[i];
transforms[i].localRotation = transformRotations[i];
}
treeDead = false;
Your answer
Follow this Question
Related Questions
Find children by tag from Player 1 Answer
How do I find out where a child is with javascript 3 Answers
Create multiple instances of an object 2 Answers
Create array of children in Start function, use it in Update? 1 Answer
Make a simple tree 1 Answer