King Duck
King Duck

Reputation: 106

Unity3D C# - Getting the type of a script

So, im created a placement system for placing objects on a grid, i have the grid and the placement all works, my issue is im trying to create a "ghost" object which exists while im placing but doesn't actually do anything, my problem is im trying to figure out a way to destroy/deactivate any and ALL "SCRIPTS" attached to any child of the ghost object, so none of them work. But i can't figure out what System.Type a script is. Anyone know?

Upvotes: 1

Views: 6913

Answers (2)

Neighborhood Ghost
Neighborhood Ghost

Reputation: 844

Using gameobject.GetComponent(typeof(Component)); will return all the components attached to that game objects but not all the components of children. However, there is a way you can get all the components of of all the children user gameObject.GetComponentsInChildren(typeof(Component));, but I don't recommend using Component instead you should use MonoBehaviour using this type you'll only get those components which are directly derived from MonoBehaviour which include your scripts as well. After that, you can check for .(dot), as almost all of the Unity's built-in components are in the namespace UnityEngine. And Object.GetType() will return the type in the following format namespace.ObjectType.

Here if you check for the index of .(dot) if the given type includes the .(dot) it will return its position. If the .(dot) don't exist in the string it will return -1. Check for the -1 we can make sure that the components are not in any namespace and is safe to destroy. I hope that you got what I'm trying to say, if not it's ok just see the code snippet below you'll get the idea.

Component[] c = ghost.GetComponentsInChildren(typeof(MonoBehaviour));
     foreach(Component cmp in c)
     {
         if(cmp.GetType().ToString().IndexOf('.') <= -1)
         {
             Destroy(cmp);
         }
     }

Upvotes: 0

user1039663
user1039663

Reputation: 1280

Call to:

gameobject.GetComponents(typeof(Component));

That will return all the components. Caution with the default Unity components: Transform, Mesh... you can determine the type with is or IsInstanceOfType or component.GetType() for cast the Component objects if necesary.

Upvotes: 1

Related Questions