- Home /
getComponentsInChildren counts fail after child destroying?
I call getComponentsInChildren after destroying some children and i obtain a wrong list of elements... This is the metacode:
// my list of components
public List<Tile> tiles;
void Awake ()
{
// here i destroy some childs
RaycastHit hit;
if (Physics.Raycast (new Vector3 (1, 1, 1), Vector3.down * 2f, out hit))
Destroy (hit.transform.gameObject);
// and here the getComponentsInChildren fails. I obtain a List with a Missing component in place of the destroyed child...
foreach (Tile t in transform.GetComponentsInChildren<Tile>())
tiles.Add (t);
}
Any hints?
Not an answer for your question, but I'll bet that if you move your foreach tothe next frame, it will work correctly. I believe, the destruction of the game objects occurs at the end of the frame. So make Awake an IEnumerator, and an a yield return null between the destroy and the foreach.
And Awake()
is really meant for the setup work you need to perform on the object that is being Awakened. Doing ray casts and Destroy in Awake make me think you're going to encounter strange problems.
Add all the possible tiles to a list, create a temp reference, remove the hit tile from the temp list, refresh the list of tiles so that hit tile doesnt exist
List<Tile> tiles = new List<Tile>();
//you can call this in awake or wherever you want if you decide you dont want it in awake
void DoTheCheck(){
Tile[] childrenTiles = transform.GetComponentsInChildren<Tile>();
foreach (Tile t in childrenTiles ){
tiles.Add(t);
}
List<Tile> temp = tiles;
tiles = new List<Tile>();
RaycastHit hit;
if (Physics.Raycast (new Vector3 (1, 1, 1), Vector3.down * 2f, out hit)){
Tile hitTile = hit.transform.getComponent<Tile>();
if(hitTile){
temp.Remove(hitTile);
}
}
for (int i=0;i<temp.Count;i++){
if(temp[i] != null){
tiles.Add (temp[i]);
}
}
}
Answer by piounity · Oct 22, 2014 at 12:11 PM
robertbu point me to the right way!
The problem was that in the same frame i can't destroy & count the same child objects! I make Destroy cycle & count cycle subroutines running one after other and now everything work in the right way!
Thank you!
Your answer
Follow this Question
Related Questions
InvalidCastException when trying to access child components 2 Answers
Cannot cast form source type to destination type? 2 Answers
GetComponentsInChilden 1 Answer
How to access a child input field from a parent prefab script. 0 Answers
BCE0019: 'GetComponentsInChildren' is not a member of 'Object'. 3 Answers