How to randomize Y position of spawned gameObject?

I'm creating a flappy bird clone as a learning exercise (I'm brand new to game dev/ unity) and I've nearly finished on my own, I just need to set it so the new pipes that spawn have a randomised position on the Y axis, how would I go about this? Attached a screenshots of the code that makes the pipes move, code that spawns the pipes and a screenshot in game showing them all on the same Y axis.
Thanks :)9794835--1405632--Screenshot 2024-04-25 133050.png 9794835--1405638--Screenshot 2024-04-25 133259.png 9794835--1405635--Screenshot 2024-04-25 133155.png

The arguments you pass to Instantiate() can be calculated values.

You can construct a new Vector3 by adding vectors, or by providing the X, Y and Z parts independently.

Vector3 calculatedOffset =
    new Vector3(0f, Random.Range(-5f, +5f), 0f);

Instantiate(pipePrefab,
    transform.position + calculatedOffset,
    transform.rotation);

Next time, share code using code tags, not a screenshot. 9841839--1416087--code-tag.png

1 Like

Thanks for the reply, I think its working but spawning to many pipes creating a giant green block. I'm going to try and figure it out myself, but do you have a solution? Here's my code now:
```
public class enemySpawner : MonoBehaviour
{
[SerializeField]
private GameObject pipePrefab;
[SerializeField]
private float minSpawnTime;
[SerializeField]
private float maxSpawnTime;

private float timeUntilSpawn;

private void Awake()
{
SetTimeUntilSpwan();
}

void Update()
{
timeUntilSpawn -= Time.deltaTime;

if (timeUntilSpawn <= 0)
{
Vector3 calculatedOffset =
new Vector3(0f, Random.Range(-5f, +5f), 0f);

Instantiate(pipePrefab,
transform.position + calculatedOffset,
transform.rotation);
}
}

private void SetTimeUntilSpwan()
{
timeUntilSpawn = Random.Range(minSpawnTime, maxSpawnTime);
}
}

I tried setting minSpawnTime and MaxSmallTime to smaller(0.0001) and larger numbers but this only changed the time taken for the green block to spawn.

fixed, i didn't reset SetTimeUntilSpwan();, once that was added after Instantiating the gameObject it worked as intended, thanks for the help.
1 Like