Im having trouble deleting a single game object from an array of game objects
I have spawner that spawns objects every 2 seconds and when the player cube moves over them I want the object that it moved over to be deleted from the array. I get all sorts of errors though.
Code using UnityEngine; using System.Collections; using UnityEngine.UI;
public class Spawner : MonoBehaviour {
public GameObject obstacle;
public GameObject player;
public int score;
private float nextSpawn;
private float spawnTime;
public Text scoring;
private GameObject obstacleDestroy;
public GameObject[] obstacles;
public int count;
void Start ()
{
scoring.text = "Score: ";
nextSpawn = 2;
}
void Update () {
obstacles = GameObject.FindGameObjectsWithTag("Obstacle");
scoring.text = "Score: " + score;
Vector3 position = new Vector3(this.transform.position.x,.1f,this.transform.position.z);
for( int i = 0; i < obstacles.Length; i++)
{
obstacles[i] = obstacleDestroy;
if (Time.time > spawnTime)
{
spawnTime = Time.time + nextSpawn;
obstacleDestroy = (GameObject)Instantiate(obstacle, position, this.transform.rotation);
count += 1;
}
}
if(obstacles[count -1] != null)
{
if(player.transform.position.x > obstacles[count - count].transform.position.x )
{
Destroy(obstacles[count - count + 1]);
count -= 1;
score += 1;
}
}
}
}
$$anonymous$$eet us half way. Post your errors.
Change your array for a List.
There are some things that don't make sense to me here.
For example:
obstacles = GameObject.FindGameObjectsWithTag("Obstacle");
...
for( int i = 0; i < obstacles.Length; i++)
{
obstacles[i] = obstacleDestroy;
You get a list of all objects with a certain tag, but before you do anything with those objects you put some other object reference into each index of the array so you lose reference to the objects you just searched for.
Then you for example check
if(obstacles[count -1] != null)
{
but since you just put obstacleDestroy to every index, that's what you'll find there.
In the end you destroy some object in the array but since the same object is put into many places, the array might become quite empty
Could you please throw in a comment or a few in the code and/or explain what you want to do and what you think the code does so we get a better idea of what the goal is.
Or maybe i'm just reading this all wrong on my mobile again :)
Destroy(obstacles[count - count + 1]);
Sooo... That would be just obstacles[1] then.
And obstacles[count - count].transform.position.x
is just obstacles[0].