Reputation: 89
How can I make the prefab2 Instanitiate at higher y than prefab1. They are spawned randomly from the same position. The code:
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Time.time > nextSpawn)
{
what = Random.Range(1, 3);
Debug.Log(what);
switch (what)
{
case 1:
Instantiate(prefab1, transform.position, Quaternion.identity);
break;
case 2:
Instantiate(prefab2, transform.position.y, Quaternion.identity);
break;
}
nextSpawn = Time.time + SpawnRate;
}
}
}
Sorry, I know the sollution is probably very simple, but I just can't find it.
Upvotes: 3
Views: 628
Reputation: 89
if (Time.time > nextSpawn)
{
what = Random.Range(1, 3);
Debug.Log(what);
switch (what)
{
case 1:
Instantiate(prefab1, transform.position, Quaternion.identity);
break;
case 2:
Vector3 tp = new Vector3(transform.position.x, -2, 0);
Instantiate(prefab2, tp, Quaternion.identity);
break;
}
nextSpawn = Time.time + SpawnRate;
}
}
Upvotes: 0
Reputation: 340
The simplest way would probably be to create a float (e.g. public float prefab2YOffset = 1f;
) and then when you instantiate prefab2, you can do something like Instantiate(prefab2, transform.position + Vector3.up * prefab2YOffset, Quaternion.identity);
. Vector3.up is shorthand for writing Vector3(0, 1, 0), and we're multiplying that vector by your desired offset on the y axis (prefab2YOffset), and adding it to the original position you would instantiate prefab2 at.
I would also recommend reading the documentation on how Vector3's work.
Upvotes: 1
Reputation: 422
There is something wrong with your Instatiate method call. In the way you are using it, the second parameter needs to be of type Vector3
and transform.position.y
is of type float
. Here is some example code that I believe you will find useful.
float spawnRate = 5f;
float spawnTime;
//how high you would like your new object to spawn above transform.position
float yValueDifference = 5f;
void Update ()
{
if (Time.time - spawnTime > spawnRate)
{
//pick a random number from 0-1
int type = Random.Range(0, 2);
Vector3 position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
if (type == 1)
position.y += yValueDifference;
//if type is 0, use prefab1, if type is 1, use prefab2
GameObject prefab = type == 0 ? prefab1 : prefab2;
Instantiate(prefab, position, Quaternion.identity);
//reset the timer
spawnTime = Time.time;
}
}
Upvotes: 1