Trying to iterate through a prefab to access its child objects
I have a 3 tier building, each tier is made up of one separate piece and these pieces are stored in an empty game object. What I am trying to do is, starting from the bottom, fade the alpha of the object to full, when the bottom one is full, move onto the second one and then the third one etc.
I am using the following code:
public GameObject basicBuildingFinishedPrefab;
private GameObject currentlyBuilding;
private iny currentPart = 0;
if (!isBuilding)
{
isBuilding = true;
currentlyBuilding = Instantiate(basicBuildingFinishedPrefab, transform.position + offset, transform.rotation) as GameObject;
}
else
{
foreach (GameObject[] child in currentlyBuilding.transform)
{
Color temp = child[currentPart].GetComponent<Renderer>().material.color;
temp.a += 0.5f * Time.deltaTime;
child[currentPart].GetComponent<Renderer>().material.color = temp;
if(temp.a >= 1)
{
currentPart++;
}
}
}
But I am getting the following error:
InvalidCastException: Cannot cast from source type to destination type.
I am getting it just at the beginning of the foreach loop. Any advice appreciated, probably overlooking something small.
Using "Prefab" is a little confusing here. If you Instantiated something from a Prefab, then it counts as a regular gameObject. You can just search "How to do X on a gameObject."
Usually, Prefab refers to the original prefab in Project. For example, some people want to change the prefab so future Instantiates will have those changes.
Answer by Munchy2007 · Jan 25, 2016 at 04:35 PM
If you want to iterate through all children and their children etc. you could approach it with recursion.
Drag this script onto any GameObject and it will debug.log the names of all children no matter how nested they are.
using UnityEngine;
using System.Collections;
public class IterateChildren : MonoBehaviour {
// Use this for initialization
void Start () {
iterateChildren(transform.root);
}
void iterateChildren(Transform trans)
{
Debug.Log(trans.name); // Do whatever logic you want on child objects here
if(trans.childCount == 0) return;
foreach(Transform tran in trans)
{
iterateChildren(tran);
}
}
}
Or you could also just use
var children = transform.root.GetComponentsInChildren<Transform>();
foreach(var child in children)
{
Debug.Log(child.name);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612061644im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Child and foreach ? 0 Answers
Using foreach while looking for tag in children 1 Answer
Looking through all the children doesn't work 1 Answer
Change layer for unparented child. 0 Answers