- Home /
Remove GameObject From Array if it already exists?
This one has been stumping me for a while now. Essentially, I have a script setup that Creates a new GameObject Array for every letter typed into a string. The problem I having now is that every time I type something the GameObject gets added too and KEEPS the original GameObject. So for example... if I type "hi". The "h" will be created twice and the "i" once.
I only want to create the "h" once... so my idea was to delete the object if it exists before instantiating it again. I should note that if I delete the string entirely, the object still remains, so I'm hoping his solves that issue as well. Here is what I have so far in the update() function.
byte[] ASCIIBytes = Encoding.ASCII.GetBytes(test);
float po = 0;
foreach (byte b in ASCIIBytes)
{
Debug.Log(test);
// check if certain "letter" already exists, if it does..
// delete it before creating it again
Instantiate(testObj[b], new Vector3(po, 0, 0), Quaternion.Euler(270, -180, 0));
po += kerning;
testObj[b].transform.tag = "Word";
}
Any help or advice would greatly appreciated. Thank you!
You are correct, I don't understand gameobject array too well. I think I know what are you are saying though. How would I create an array element in this example? Would this allow me to create "one" gameobject in the scene with several subobjects?
Answer by whydoidoit · Oct 15, 2012 at 09:08 PM
Yes that would happen! You will need to delete all of the letters you created before. When you instantiate them add them to a List<GameObject> and the next time - delete all the existing ones before creating the new ones.
Thanks for the response $$anonymous$$ike! I think I understand what are suggesting. I just have never used List<> before. How would I add the gameObjects to a List?
Would something like this work?
List<GameObject> temp = new List<GameObject>(b);
You would create the list as a private variable of the class:
List<GameObject> currentLetters = new List<GameObject>();
You would add them as you instantiate them:
currentLetters.Add(Instantiate(testObj[b]...));
But before you created the new ones you would do:
foreach(var letter in currentLetters)
Destroy(letter);
currentLetters.Clear();
Now this all presumes that testObj[] is an array of GameObjects - it it's something else then you would need to get the gameObject from it. Eg. testObj[] is an array of Transform then:
currentLetters.Add((Instantiate(...) as Transform).gameObject);
There info on using Lists here
Thanks so much $$anonymous$$ike!!
I was able to use this
currentLetters.Add((Instantiate(testObj[b], new Vector3(po, 0, 0), Quaternion.Euler(270, -180, 0)) as GameObject));
and it did the trick perfectly! In combination with your suggested foreach code.
=)