4 different gameObjects, randomly spawned but should be possible to do stuff with them.
hey! im learning unity by making a timberman game - you have a character, and a tree. The tree consist of either a left branch, a right branch or a "no branch tree piece". The players job is to chop down the tree and dodging the branches by going to the other side of the tree (clicking the other side). Now here's my problem:
I want to randomly spawn tree pieces. There should be 4 pieces on the scene at all times, but only the one closes to the ground should be destroyed at each mouse click. The one above the destroyed one should move down and become the new "closes to the ground piece", and at the same time a new piece should be spawned.
I've been trying to do this with prefabs but from the unity guide im not sure how to save the objects inorder to lower their y coordinates for each mouseclick etc.
TL;DR: 4 random gameObjects in scene at all times, want to lower their y coordinates for each mouseclick and destroy the furthest down object, and at the same time spawn a new random object at the top.
Answer by Jessespike · Jun 07, 2016 at 07:44 PM
Store the spawned objects in a List. Move the objects when mouse is clicked. This isn't complete code, but it should be something to get you started.
public Transform[] branches;
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
foreach(Transform branch in branches)
{
branch.localPosition += new Vector3(0f, -1f, 0f);
if (branch.localPosition.y < -5f)
{
Respawn(branch);
}
}
}
}
void Respawn(Transform branch)
{
branch.localPosition = new Vector3(
Random.Range(-2f, 2f),
Random.Range(4f, 6f),
10f);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612082439im_/https://answers.unity.com/themes/thub/images/avi.jpg)