Translate in the TreeSpawner

I fought this one a bit, as the TreeSpawner was not properly placing the trees in lanes that were spawned after the first position.

I solved the issue, by spawning the trees in the Awake, instead of Start function.
Later I found that Ben resolved it by changing Translate to transform.localPosition

Just another way to dissect a frog. I believe calling at Awake let’s the Tree’s be properly oriented in the Lane before Lane gets moved to final location.


Full code can be found at: https://tbookout@bitbucket.org/tbookout/squashy-toad.git
Commit = 68
Though I did change back to match course.
Inadvertently I also did work that is covered in next lesson.


public class TreeSpawner : MonoBehaviour {

public GameObject treePrefab;
public int minTreeCnt;
public int maxTreeCnt;


// Spawning on Start does not properly move child with parent
void Awake()
{
    SpawnTrees();
}

void SpawnTrees ()
{
        int treeSpawnCnt = Random.Range(minTreeCnt, maxTreeCnt);
        for (int icnt = 0; icnt < treeSpawnCnt; icnt++)
        {
            float x_Offset = Random.Range(-45f, 45f);
            float z_Offset = Random.Range(-4f, 4f);

            var tree = Instantiate(treePrefab);
            tree.transform.parent = transform;
            
            tree.transform.Translate(x_Offset, 0f, z_Offset);

            float treeScale = Random.Range(.15f, .3f);
            tree.transform.localScale = new Vector3(treeScale, treeScale, treeScale);
        } 
}

}

Privacy & Terms