Get Components without parent?

Hello, quick question!

Sorry if that’s too basic, I looked into the documentation and I couldn’t find a function or method that returns the Components in a gameobject without the parent gameobject.

Thank you for your answers.

You can do this:

var comps : yourType[];
comps : GetComponentsInChildren.<yourType>();

for(var comp : yourType in comps)
{
   // Is my ID (the parent) not the same as the component's gameObject
   if ( comp.gameObject.GetInstanceID() != GetInstanceID() )
   {
   }
}

Or in C#:

YourType[] comps = GetComponentsInChildren<yourType>();
foreach (YourType comp in comps)
{
       if ( comp.gameObject.GetInstanceID() != GetInstanceID() )
       {
       }
}

Here is a script that allows you to get all child script except the root object which I assume is what you meant by parent object (the very top one)

using UnityEngine;
using System.Collections;
using System.Collections.Generic; //Necessary!!!!

public class NPCScript : MonoBehaviour {
	
	void Start(){
		HealthScript [] sc = GetCompNoRoot<HealthScript>(gameObject);
		foreach(HealthScript s in sc){
			s.health = 10;
		}
	}
	
	T[] GetCompNoRoot<T>(GameObject obj)where T:Component{
		List<T> tList = new List<T>();
		foreach (Transform child in obj.transform.root)
   		{
   			T[] scripts = child.GetComponentsInChildren<T>();	
			if(scripts != null) {
				foreach(T sc in scripts)
					tList.Add (sc);
			}
    	}
		return tList.ToArray();
	}
}

The method is GetCompNoRoot. It takes the script name as generic parameter and I added a game object parameter in case you wold store that method somewhere else like a Utility file.

All it does is create a list, get the root object of the parameter object and starts going down the hierarchy. In the end it returns an array of all scripts found.

Now if you meant no parent object as in no parent object simply gets this

foreach (Transform child in obj.transform.root)

to

foreach (Transform child in obj.transform)

Then if the script is on a child object in a hierarchy, it will ignore anything above but will go down also ignoring the object to which it is attached.

Note that this will work with any script or Component because of the constraint (where T: Component).