- Home /
How can instantiate in set random places?
Hello!
As the question states, I need to instantiate in random places. I know that I have asked a question like this before, but I felt that this should have its own question.
I have used some code from answers in that previous question, and here is the current code:
#pragma strict
var choosingIsActive : boolean = true;
public var spawnPoints : Transform [];
public var prefab : GameObject;
var standByCamera : GameObject;
var playerCamera : GameObject;
var monsterPrefab : Transform;
function Start () {
}
function Update () {
}
public function OnGUI()
{
if(choosingIsActive)
{
if(GUI.Button(Rect(Screen.width/2.1, Screen.height/2.1, 106, 50), "Play!"))
{
choosingIsActive = false;
standByCamera.SetActive(false);
playerCamera.SetActive(true);
}
if(GUI.Button(Rect(Screen.width/2.1, Screen.height/1.8, 106, 50), "10 Monsters"))
{
var indx: int = Random.Range(0,spawnPoints.Length-1);
var spawnPosition : Vector3 = spawnPoints[indx].position;
for (var i : int = 0; i > 10; i++) {
Instantiate(monsterPrefab, spawnPosition, Quaternion.identity);
}
}
}
}
I don't get any errors, but when I press on the 30 Monsters button nothing happens. Even when I press Play there is nothing there. I look in the Hierarchy and there is nothing added to it.
I have searched Google an d Unity Answers to try and find help, but I haven't been able to find anything.
Can anybody help me please?
Thanks in advance!
Answer by InvincibleCat · Jan 12, 2015 at 10:25 PM
it's i < 10 and no i > 10 (and 10 should be a variable representing the number of monsters you want to instantiate) And if you want your monsters to spawn at different positions, you should do
var indx: int = Random.Range(0,spawnPoints.Length-1);
var spawnPosition : Vector3 = spawnPoints[indx].position;
in your for loop
Cheers
Ok thanks. But one more thing. How do I define the variable for 10? Where do I do it? Thanks!
Actually, since Random.Range with ints as parameters excludes the max value, it should be
var indx: int = Random.Range(0,spawnPoints.Length);
(so, without the "-1" since random int will never reach the Length of the array anyway :) )
You should also be aware that the way the code currently works is that all 10 monsters will spawn at the same (random) spot. Is that really what you want, or do you want to have a random sport for each of the 10 monsters?
lol @Cherno you should have read my comment first (for the random part n_n)
This is great thanks guys :) Also, @Cherno to answer your question, yes I want my monsters to be in different random spots. Only a few should be in the same spot. Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613180234im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
one prefab into random position of grid 0 Answers
random prefab instantiation 2 Answers