Hey guys so I'm new to C# and our professor just assigned us homework, and I'm trying to figure out how to get the object to drop randomly within a certain range but I don't know so can someone help me he gave us this code:
using UnityEngine; using System.Collections;
public class SpawnerScript : MonoBehaviour {
public GameObject ball1Prefab;
private float spawnTimer;
private float spawnCounter;
void Start()
{
spawnTimer = 1.0f;
spawnCounter = 0.0f;
}
void Update () {
spawnCounter += Time.deltaTime * 1;
if (spawnCounter >= spawnTimer) {
SpawnEgg ();
spawnCounter = 0;
}
}
void SpawnEgg()
{
Instantiate (ball1Prefab, transform.position, Quaternion.identity);
}
}
Could you specify your problem?
You mean drop within a certain range of position? And if so, what kind of range? Should we give a certain amount of range on all axes so it can be placed anywhere within a rectangle, or within a circle?
Sorry, what I mean by a certain range is like...ok so the code is for a invisible spawner that right above the game screen, and this is a left to right moving game in a 3D environment. So I guess the best I can explain it is, I want that spawner to spawn objects randomly on the X axis without going out of the game screen...I don't know if that helped but I'm kinda new at all this so sorry.
Answer by WTler · Jun 20, 2017 at 10:56 PM
Probably much to late, but it would have been something like this:
void SpawnEgg()
{
float Min = -5f, Max = 5f;
Vector2 newPos = new Vector2(Random.Range(Min, Max), 10);
Instantiate(ball1Prefab, transform.position + newPos, Quaternion.identity);
}
Your answer
Follow this Question
Related Questions
Spawn objects from picture isnt working 1 Answer
How do I spawn a List of Objects, so that there is a delay after each object that spawned? 0 Answers
How do I spawn a List of Objects so that there is a delay after each object that spawned? 0 Answers
How to change Button input to Keyboard input? 1 Answer
Spawn different obstacles 0 Answers