- Home /
How to make objects appear with mouse click in a row?
Hey, I'm new with C# and I'm trying to figure out how to spawn objects with mouse click in a row. So each click would spawn the same object next to the previous object endlessly.
Any help would be greatly appreciated!
Answer by sean244 · Apr 13, 2018 at 01:20 AM
Drag the gameobject that you want to spawn from the hierarchy to the assets window. This will create a prefab out of it. Then create another gameobject and attach a script to it. Include the following code inside of that script
[SerializeField]
private GameObject _spawnPrefab;
private List<Transform> _targets = new List<Transform>();
private void Start()
{
_targets.Add(_spawnPrefab.transform);
}
private void Update()
{
Spawn();
}
private void Spawn()
{
if (Input.GetMouseButtonDown(0))
{
GameObject go = Instantiate(_spawnPrefab, _targets.LastOrDefault().position + new Vector3(_spawnPrefab.GetComponent<Renderer>().bounds.size.x, 0f), Quaternion.identity);
_targets.Add(go.transform);
}
}
Go back to the editor and select the gameobject that this script is attached to. In the inspector, you should see an empty box called 'Spawn Prefab'. Drag and drop that prefab that you created earlier into the box. It should work now. If this answer was helpful, please click 'Accept' :)
Works just like I wanted ty so much! One more thing is it possible to make background loop and camera follow those gameobjects? :) And what I mean by that is that camera would always be on the latest gameobject. And is there a way that it could erase old gameobjects when those are away from the screen? It feels like it takes lots of memory after couple times repeating spawning process or is it just unity that it cant handle that much?
Post this as its own question, and I'll see if I or someone else can help you with it :)
Answer by vilzzzu_unity · Apr 13, 2018 at 02:47 AM
That was really quick answer thank you so much!
Works just like I wanted ty so much! One more thing is it possible to make background loop and camera follow those gameobjects? :) And what I mean by that is that camera would always be on the latest gameobject. And is there a way that it could erase old gameobjects when those are away from the screen? It feels like it takes lots of memory after couple times repeating spawning process or is it just unity that it cant handle that much?
It gives me Fatal Error what says: "Size overflow in allocator" after ~14 times repeating the process.In hierarcy it spams that gameobject(Clone)Clone)(Clone)(Clone)(Clone)(Clone).. Like ALOT the only component besides that script is Box Collider 2D. I earlier had Rigidbody 2D aswell but it seems like that script multiplies each time when used those current gameobjects.
Your answer
Follow this Question
Related Questions
2d spawn across screen 1 Answer
Multiple Cars not working 1 Answer
Spawn random Obstacles along the x-axis 0 Answers
Instantiating at different rates 1 Answer