- Home /
Other
Question about Instantiate
Hello and thanks for stopping by, here's my scene starting point :
I'm trying to instantiate prefabs in my scene and make them spawn around the initial prefab (the square in the image).
I've got a somewhat working code that does instantiate the prefab under it, and I now know how to make it spawn around. The problem is that it's not scalable : I would have to write in my code the position of each prefab...
Any ideas on how to do that ? Thanks for reading.
(Here's my current code) :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawning : MonoBehaviour {
public GameObject Tile;
[SerializeField] private int TotalTilesSpawned = 0;
[SerializeField] private float xAxis = 0f;
[SerializeField] private float yAxis = - 2f;
void Update(){
if (Input.GetKeyDown("s")){
Instantiate(Tile, new Vector2 (xAxis, yAxis), transform.rotation);
TotalTilesSpawned += 1;
yAxis -= 2;}
}
}
Answer by Mrnoobik · Apr 28, 2020 at 02:36 PM
You can do this:
public List <Vector2> positions = new List<Vector2>();
And then in Update():
Instantiate(Tile, new Vector2 (xAxis, yAxis), transform.rotation);
positions.Add (new Vector2(xAxis, yAxis));
Hope this helps you.
Thanks for answering ! Your solution helps keeping track of the positions of each instantiated tile but doesn't solve my initial problem : how can I make them spawn all around the first tile in an infinite number without having to write it's coordinates for each tile ? Example : Here's the scene when starting : And here's the scene after some tiles got spawned : Please excuse my lack of photoshop skills ^^
Thanks for the help !