- Home /
Random enemy spawning without using a radius?
So I am trying to make my enemys spawn in completly random parts along the x value. So I want them to always spawn at the same z and same y values, but a random x. How would I go about doing this. Also if you could incorporate how I would make the enemys that spawn also be random out of a 1,2,and 3 instance that would be great! PS. I am using JS
Answer by Ambro · Dec 04, 2013 at 08:22 PM
You should try to use the Random class for that.
For example, if you want to instantiate a prefab randomly along the x-axis, you could go like that (sorry it's in C# but it must be pretty close in JS) :
float randomXValue = Random.Range(minimalRandomValue,maximalRandomValue);
GameObject.Instantiate(myPrefab,new Vector3(randomXValue,constantY,constantZ),Quaternion.identity);
For choosing among three instance, you could store those 3 instances in an array and do that :
int instanceChoice = (int)(Random.Range(0,myInstanceArray.Length-0.1f));
float randomXValue = Random.Range(minimalRandomValue,maximalRandomValue);
GameObject.Instantiate(myInstanceArray[instanceChoice],new Vector3(randomXValue,constantY,constantZ),Quaternion.identity);
thanks, but how would I speacify where on the z and y axis? or would it just be where ever the parent gameobject is?
Just replace the variable named constantY and constantZ by what you want. It could be a constant, a class variable that you defined in the inspector, or you can use like you said the transform of this gameobject.
Something like :
new Vector3(randomXValue,transform.position.y,transform.position.z);
An other solution would be to have an array of Transform which would be spawn point and use the Y and Z position of those transform to instantiate your object.
Your answer
Follow this Question
Related Questions
Access a instantiated gameobject from a enemy spawner 4 Answers
Help with Enemy Spawner! 3 Answers
Urgent Help Needed: Enemy Spawning and Movement 1 Answer
Help with Enemy Spawner! 1 Answer
Enemy Spawning and Movement 0 Answers