- Home /
How to make background loop and camera follow spawned gameobjects?
How to make background loop and camera follow gameobjects? And what I mean by that is that camera would always be on the latest gameobject. It feels like it takes lots of memory after couple times repeating spawning process so I will need some way to erase past gameobjects which are out of screen. Im new with C# so any help would be greatly appreciated!
So first of all Im using this script to spawn gameobjects:
[SerializeField]
private GameObject _spawnPrefab;
private List<Vector3> _targets = new List<Vector3>();
private void Start()
{
_targets.Add(_spawnPrefab.transform.position);
}
private void Update()
{
Spawn();
}
private void Spawn()
{
if (Input.GetMouseButtonDown(0))
{
GameObject go = Instantiate(_spawnPrefab, _targets.LastOrDefault() + new Vector3(_spawnPrefab.GetComponent<Renderer>().bounds.size.x, 0f), Quaternion.identity);
_targets.Add(go.transform.position);
}
I would like to make the script to work endlessly now it gives Fatal Error what says: "Size overflow in allocator" after ~14 times repeating the spawning 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.
Answer by Harinezumi · Apr 13, 2018 at 08:57 AM
To be able to follow an object even after it has moved, you need to store its Transform. So change the type of _targets
to List<Transform>
and the last line in Spawn()
to _targets.Add(go.transform);
. Then to get the last transform for your camera to follow I would write the following function:
public Transform GetLastTarget () {
if (_targets.Count > 0) { return _targets[_targets.Count - 1]; }
return null;
}
You can use the transform.position
from GetLastTarget()
for following with your camera. Make sure you check that GetLastTarget()
didn't return null!
Good luck!
Thanks for replying! I will try that when I get back to home.
Harinezumi's solution should work. If you have trouble implementing it, give me your email and we can arrange a Skype and Teamviewer session to help you out.
I'm a bit stuck here.
Your help would be much appreciated. Vilzzzu@gmail.com
Your answer
![](https://koobas.hobune.stream/wayback/20220612160640im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Enemies spawn on top of each other(C#)(Unity) 1 Answer
AI spawning areas. What are the ways to make them? 1 Answer
Instantiate is throwing my throwing my objects? 1 Answer
Enemy spawn, round based 1 Answer
Hide gameobject? 1 Answer