- Home /
Question by
latsushi · Oct 01, 2018 at 04:32 AM ·
instantiaterandom.rangegetmousebuttondown
Spawn An Object Every 2 Units On The Y-Axis
Right now, the script I have behaves like this... When you click the left mouse button a cube (prefab) spawns at my desired spawn position represented by the Transform variable 'spawnPos'. What I'm trying to accomplish is to click the mouse button, have the first cube spawn at the desired spawn position (which it's currently doing), and then each time the mouse button is clicked after that, have the cube spawn 2 units fewer on the y-axis.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomSpawner : MonoBehaviour {
public GameObject[] spawnees;
public Transform spawnPos;
int randomInt;
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown(0)) // 0 is left mouse button
{
SpawnRandom();
}
}
void SpawnRandom()
{
randomInt = Random.Range(0, spawnees.Length);
Instantiate(spawnees[randomInt], spawnPos.position, spawnPos.rotation);
}
}
Comment
Best Answer
Answer by Hellium · Oct 01, 2018 at 04:58 AM
public Vector3 DeltaPosition = -2 * Vector3.up ;
private int instancesCount = 0 ;
void SpawnRandom()
{
randomInt = Random.Range(0, spawnees.Length);
Vector3 position = spawnPos.position + DeltaPosition * instancesCount++ ;
Instantiate(spawnees[randomInt], position, spawnPos.rotation);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612175534im_/https://answers.unity.com/themes/thub/images/avi.jpg)