- Home /
How to get randomly spawning objects across a map
Recently I have been coding a game that requires you to pick up collectibles across a map. As I am fairly new to c#, I really can't work it out and i cant get the objects to distribute. Also having some trouble with quaternions. I would really appreciate some help. It's made in top down 2D. code:
public Object Wood;
public Transform WoodP;
public Vector3 woodpos = new Vector3(Random.Range(100, -100), Random.Range(100, -100), 0);
void Update()
{
Instantiate(Wood, woodpos, Quaternion.Euler(Random.Range(0, 360), 0, 0), WoodP);
}
Answer by knobblez · Jan 26, 2020 at 05:39 AM
Update is a crazy place to put that. It's gonna spawn an insane amount of objects. I would use a variable like:
int spawnCount;
and put in a for loop so it only spawns a certain amount. Put that in a function() and just call it when you need it instead of every frame.
As for the code, that looks like it should work.
For rotation, I would probably use eulerAngles: https://answers.unity.com/questions/790877/random-rotation-in-z-axis.html
Answer by edgib102 · Jan 26, 2020 at 10:51 PM
So I did that (minus the rotation) and it completely bugs out spawning massive objects, and crashing the game (not sure how big they are, could just be a visual glitch)
Code:
public Object Wood;
public Transform WoodP;
public int Spawncount = 5;
int spawnLimit = 0;
public void Update()
{
if (spawnLimit != Spawncount || spawnLimit <= Spawncount)
{
WoodGen();
spawnLimit++;
}
}
void WoodGen()
{
Vector3 woodpos = new Vector3(Random.Range(100, -100), Random.Range(100, -100), 0);
Instantiate(Wood, woodpos, Quaternion.Euler(Random.Range(0, 360), 0, 0), WoodP);
}
}
Your answer
Follow this Question
Related Questions
Rotate a cloned object with key press 1 Answer
Trying to Clone 1 of 5 GameObjects in a array 1 Answer
Instantiate Reference Problem 1 Answer