- Home /
"FindObjectsOfType" in specific gameObject only?
Hi all, quick question about "FindObjectsOfType"...right now the way it's being used returns all objects of type T[] in the scene:
public GameObject myGO;
void Awake(){
foreach(GameObject go in FinObjectsOfType(typeof(GameObject)) as GameObject[])
{
if (go.name == "The Name I'm Looking For")
{
myGO = go;
}
}
}
Returning all GameObjects in the scene when I'm only looking for only 1 object, which I know is a child of another GameObject, is a huge waste of time. So is there a way to do this:
public GameObject myGO; private GameObject playerObj;
void Awake(){
playerObj = GameObject.FindWithTag("Player");
foreach(GameObject go in playerObj.FinObjectsOfType(typeof(GameObject)) as GameObject[])
{
if (go.name == "The Name I'm Looking For")
{
myGO = go;
}
}
}
That way "FindObjectsOfType" only looks in the "playerObj" GameObject for objects of type "GameObject" instead of looking through the entire scene.
Also, is "FindObjectsOfType" faster the "GameObject.Find" ?
Thx for any help in advance! Stephane
Answer by e-bonneville · Mar 31, 2011 at 05:59 PM
If I'm reading you right, you just want to find a specific gameObject from the children of playerObj. If that's the case, then you could do something like this:
public GameObject myGO; private GameObject playerObj;
void Awake(){
playerObj = GameObject.FindWithTag("Player");
childTransforms = playerObj.GetComponentsInChildren<Transform>();
foreach(Transform currentChildTransform in childTransforms)
{
if (currentChildTransform.gameObject.name == "The Name I'm Looking For")
{
myGO = currentChildTransform.gameObject.name;
}
}
}
Please note, the above is untested C# and may contain errors.
Yes the "GetComponent" method is the way to go for this! It's a lot faster then looking up every object type in the scene...thanks for your help Elliot!
Yup. Remember, if this works for you, please don't hesitate to accept this as the correct answer and upvote it. :)