I’m actually developping my first game on Unity and as I do some codes to initiate a prefabs. The thing is that I still need to have access or at least create a GameObject variable to refer to the childs of the prefabs I previously created.
To shorten what I ask:
I want to create a prefabs during runtime with C# (No need to specify anyway to generate it, I have my own idea)
I want to have access to the prefabs children
I want to be able to modify some parts of the prefabs children
And if I’m still not clear enough:
I want to initiate a shoe. I want to have access, for example, to the lace Prefabs of the shoe I have initiated. But I also want to have access to other parts individually (Like the sole of it) to be able to color them individually! I already have made the code to color them, I only need to get the way to initiate the shoe and get his children individually to modify them as well!
If you still don’t understand me, I can try to make another explanation on demand! Thanks for your help!
Hello there,
If you have a reference to the GameObject, it’s very simple. You could do:
public GameObject prefab_shoe = null;
public Vector3 v3_spawnPos = Vector3.zero;
private void CreateShoe()
{
GameObject newShoe = Instantiate(prefab_shoe, v3_spawnPos, Quaternion.identity) as GameObject;
List<GameObject> laces = new List<GameObject>();
List<GameObject> sole = new List<GameObject>();
for (int i = 0; i < newShoe.transform.childCount; ++i)
{
Transform currentItem = newShoe.transform.GetChild(i);
//Search by name
if (currentItem.name.Equals("laces"))
{
laces.Add(currentItem.gameObject);
continue;
}
if (currentItem.name.Equals("sole"))
{
sole.Add(currentItem.gameObject);
continue;
}
//Search by tag
if (currentItem.CompareTag("laces"))
{
laces.Add(currentItem.gameObject);
continue;
}
if (currentItem.CompareTag("sole"))
{
sole.Add(currentItem.gameObject);
continue;
}
//Search by component
if (currentItem.GetComponent<Laces>() != null)
{
laces.Add(currentItem.gameObject);
continue;
}
if (currentItem.GetComponent<Sole>() != null)
{
sole.Add(currentItem.gameObject);
continue;
}
}
// Do something with the results here
if(laces.Count > 0)
{
// Do something with the laces
}
if(sole.Count > 0)
{
// Do something with the soles
}
}
This way, you get every single child that corresponds to our criteria (I’m not sure why you would have multiple soles, but you could have multiple buttons for example).
Hope that helps!
Cheers,
~LegendBacon