x


Remove an object from an array and destroy it (C#)

Hey Guys, i'm with a problem here. I just can't hold the last object of an array(not his index, but the object attached to this index) and destroy it. I find out how to remove it from the array but I don't managed to remove it from the scene. If you guys want, here's the code ( Some variable names are in portuguese );

using UnityEngine;

using System.Collections; using System.Collections.Generic;

public class Teste : MonoBehaviour {

public List<GameObject> objetos;
public int deslocamento;
public GameObject prefabObjeto;

// Use this for initialization
void Start () {

objetos = new List<GameObject>();

}

void removerArray (int posicao) {

objetos.RemoveAt (posicao);

}

// Update is called once per frame
void Update () {

if(Input.GetButtonUp ("Fire1")) 
    {
    deslocamento += 10;
    GameObject newObj;
    newObj = (GameObject)Instantiate (prefabObjeto, transform.position, Quaternion.identity);
    newObj.transform.position = (new Vector3(0 + deslocamento, 30, 0));
    objetos.Add (newObj);
    }
    else if (Input.GetButtonUp("Fire2") && (objetos.Count > 0))
    {
    int ultimoObjeto;
    ultimoObjeto = objetos.Count - 1;
    removerArray(ultimoObjeto);
    }

}

}

Variable meaning in English

objetos = objects. posicao = position. prefabObjeto = objectPrefab. deslocamento = displacement.

Hope yous guys may help me out in this. Thanks from now!

*Sorry for my bad English.

more ▼

asked Jan 12 '12 at 03:58 PM

GutoThomas gravatar image

GutoThomas
593 32 46 47

(comments are locked)
10|3000 characters needed characters left

2 answers: sort newest

You need to call Object.Destroy when removing the object from the list. Also you should test if posicao is not equal or greater than objetos.Count

void removerArray (int posicao) {

  if(posicao >= 0 && posicao < objetos.Count) {

    Destroy(objetos[posicao]);
    objetos.RemoveAt (posicao);

  }
}
more ▼

answered Jan 12 '12 at 06:08 PM

luizgpa gravatar image

luizgpa
851 4 9

(comments are locked)
10|3000 characters needed characters left

Thanks, it works perfectly! :D

more ▼

answered Jan 12 '12 at 11:17 PM

GutoThomas gravatar image

GutoThomas
593 32 46 47

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2090
x1363
x1281
x764
x91

asked: Jan 12 '12 at 03:58 PM

Seen: 3192 times

Last Updated: Jan 12 '12 at 11:17 PM