- Home /
How to NOT get components from grandchildren ?
Hello everybody. I'm working on a load/save sub-system for a game, and I want the saves to save the transform data of various items that are in the scene. So here's what I've done: I added all items that are in the scene in a single gameObject named 'Items', and I use GetComponentsInChildren<>() to get the transforms. So when a save file is loaded, the script finds the 'Items' gameObject, runs GetComponentsInChildren<>(), and if the name of the gameObject in the save file is the same as the name of the gameObject of a particular transform in the array that is returned by GetComponentsInChildren<>(), it changes the transform data to the ones of the save file.
There is a problem though. You see, the items are gameObjects that have their own children, often things like LOD meshes, or other meshes that become visible under certain circumstances etc. And GetComponentsInChildren<>() not only returns the transforms of the children, but also the grandchildren. And that is a problem. Because a child gameObject of an Item object may contain a gameObject with the exact same name as the child gameObject of another Item. So if you have like some instances of an Item in the scene, the meshes of all move to one single position, making all instances but one to be 'invisible'.
So, is there an easy way to get all the components of children ONLY, and not the grandchildren ? Please tell me there is one.
Answer by Hellium · Nov 21, 2017 at 02:22 PM
Try the following solution (not tested)
Create a new C# file called GameObjectExtensions.cs and put the following code
using UnityEngine;
using System.Collections.Generic;
public static class GameObjectExtensions
{
public static T[] GetComponentsInDirectChildren<T>( this GameObject gameObject ) where T : Component
{
List<T> components = new List<T>();
for( int i = 0 ; i < gameObject.transform.childCount ; ++i )
{
T component = gameObject.transform.GetChild( i ).GetComponent<T>();
if( component != null )
components.Add( component ) ;
}
return components.ToArray();
}
}
Then, in your code :
MyScript[] scripts = gameObject.GetComponentsInDirectChildren<MyScript>();
Your answer
Follow this Question
Related Questions
grab weapon script problem 1 Answer
Storage of children references efficiency 1 Answer
GetComponentsInChildren not working 0 Answers
trouble getting all children into an array. 1 Answer
short script error mesige 1 Answer