So I have an infinite spawner based on distance that spawns an object every time the previous object is 10 units away, but this only works for the X spacing and does not allow me to alter the Y spacing, therefore I have to alter it afterwards. It will all make sense once you read the code.
What happens is that when I use SpawnedObject.transform.position = transform.position;, the spacing is all fine and dandy, but when I use SpawnedObject.transform.position = SpawnPosition(-10, 10);, the position.x starts to get crazy and erratic. Meaning it will spawn like 2 units away, or sometimes 6 and so on.
Why is it doing this and how can I fix it?
Here is a picture of the problem http://imgur.com/YIXSK8X
The logs are supposed to be separated by 1 square which is 10 units.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// This script creates a list of type objects and allows you to use the objects in that list.
public class ObjectPool : MonoBehaviour
{
//when using this for other GameObjects, just change the class name to _w/e.
public static ObjectPool instance;
public GameObject _object;
public int poolAmount = 20;
public bool willGrow = true;
public float newSpeed;
public List<GameObject> pooledObjects;
public float distance;
public int ObjectSpacing;
private GameObject SpawnedObject;
private float randomXPosition;
private float randomYPosition;
void Awake()
{
instance = this;
}
// Use this for initialization
void Start()
{
pooledObjects = new List<GameObject>(); //create object pool
for (int i = 0; i < poolAmount; i++)
{
var obj = (GameObject)Instantiate(_object);
obj.SetActive(false);
pooledObjects.Add(obj);
}
SpawnNextObject(); //Spawn first object
}
void Update()
{
distance = Vector2.SqrMagnitude(SpawnedObject.transform.position - transform.position); //calculate distance between this object and objectpool start position
if (distance > (ObjectSpacing*ObjectSpacing))
{
SpawnNextObject();
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < pooledObjects.Count; i++)
{
if (!pooledObjects*.activeInHierarchy)*
{
return pooledObjects*;*
}
}
if (willGrow)
{
GameObject obj = (GameObject)Instantiate(_object);
pooledObjects.Add(obj);
return obj;
}
return null;
}
private void SpawnNextObject()
{
SpawnedObject = GetPooledObject();
//SpawnedObject.transform.position = transform.position;
SpawnedObject.transform.position = SpawnPosition(-10, 10);
SpawnedObject.SetActive(true);
}
Vector2 SpawnPosition(float minY, float maxY)
{
if (minY != maxY)
{
randomYPosition = Random.Range(minY, maxY);
}
else
{
randomYPosition = minY;
}
var obstaclePos = new Vector2(transform.position.x, randomYPosition);
return obstaclePos;
}
}