Hello, I’m making a 2D infinite vertical game with a jetpack and I have a script that spawns coins and boosters when the object count is less than my desired amount. The problem is that after the first round of objects spawn, the next objects are spawning very far in the y axis and I don’t know why. Here are the scripts for spawning and for decreasing count. Would appreciate any help as this is my first project so I’m quite new
public class Spawner : MonoBehaviour
{
[SerializeField] GameObject[] prefabs;
[SerializeField] float spawnDelay = 3f;
[SerializeField] int count = 0;
[SerializeField] int itemsPerScreen = 20;
[SerializeField] float yOffset;
Vector3 screenPos;
Vector3 previousPosition;
private void Start()
{
previousPosition = transform.position;
InvokeRepeating("spawnPrefab", spawnDelay, spawnDelay);
}
public void minusCount()
{
count--;
}
void spawn(float minXPos, float maxXPos, float chance, GameObject prefab)
{
if (Random.value <= chance)
{
Vector3 finalPos;
if (Random.value <= 0.5)
{
finalPos = new Vector3(Mathf.Clamp(screenPos.x + previousPosition.x, minXPos, maxXPos), screenPos.y + previousPosition.y, transform.position.z);
}
else
{
finalPos = new Vector3(Mathf.Clamp(screenPos.x - previousPosition.x, minXPos, maxXPos), screenPos.y + previousPosition.y, transform.position.z);
}
GameObject stuff = Instantiate(prefab, finalPos, Quaternion.identity);
previousPosition = new Vector3(Mathf.Clamp(stuff.transform.position.x, -2.22f, 2.22f), stuff.transform.position.y - yOffset, stuff.transform.position.z);
count++;
}
}
public void spawnPrefab()
{
screenPos = Camera.main.ViewportToWorldPoint(new Vector3(Mathf.Clamp(Random.Range(0.1f, 0.7f), -2.22f, 2.22f), Random.Range(1.1f, 2), 10));
foreach (GameObject thing in prefabs)
{
if (count < itemsPerScreen)
{
if (thing.GetComponent<Booster>())
{
spawn(-2.22f, 2.22f, 0.2f, thing);
}
if (thing.GetComponent<CoinBooster>())
{
spawn(-2.4f, 1.13f, 0.6f, thing);
}
if (thing.GetComponent<Coin>())
{
spawn(-2.22f, 2.22f, 0.4f, thing);
}
if (thing.GetComponent<Coins>())
{
spawn(-1.92f, 1.92f, 0.3f, thing);
}
}
else
break;
}
}
Code for decreasing:
public class Item : MonoBehaviour
{
[SerializeField] float yOffsetForDeletingObject = 5f;
Spawner spawner;
private void Start()
{
spawner = FindObjectOfType<Spawner>();
}
private void Update()
{
if(transform.position.y < Camera.main.transform.position.y - yOffsetForDeletingObject)
{
spawner.minusCount();
Destroy(gameObject);
}
}
}
Thanks!