- Home /
C# 2d Instantiate object randomly around gameobject
Hello! I think that there probably is a simple solution to this, but, browsing google and different threads around here, I just get more confused, rather than enlightened.
So this is what my Random instantiate code looks like:
void Start () {
InvokeRepeating("Spawn", SpawnStartDelay, SpawnRate);
}
void Spawn() {
Vector2 position = new Vector2(Random.Range(-10.0F, 10.0F),Random.Range(-10.0F, 10.0F));
Instantiate(enemyPrefab, position, Quaternion.identity);
So, how do I reference a "this.gameobject.transform.position" in this kind of script? I've been trying different things without success. They just spawn randomly on axis 0,0, as expected.
Answer by SarperS · Oct 22, 2014 at 12:39 AM
const float range = 10.0f;
private void Spawn() {
var randomPos = Random.insideUnitSphere * range;
randomPos.y = 0;
Instantiate(enemyPrefab, transform.position + randomPos, Quaternion.identity);
}
Thank you! This did work. But, in my topdown 2d game I would have to use randomPos.z = wanted value.
And for someone using C#, this is what the code ended up looking like:
private void Spawn() {
Vector3 randomPos = Random.insideUnitSphere * range;
randomPos.z = -1;
Instantiate(enemyPrefab, transform.position + randomPos, Quaternion.identity);
Your answer
Follow this Question
Related Questions
C# GameObjects Instantiate Into Each Other Issue 1 Answer
How to randomly spawn three non repeating gameobjects from an array? 2 Answers
What is the best way to instatiate an array of connected GameObjects? 0 Answers
FPS Object-on-wall Placement 0 Answers
instantiate prefabs y+1 from last instintiated prefab 1 Answer