Making "GetComponent<*Type*>" Reusable and Assigning *Type* in the inspector

hello, im trying to make a script that checks conditions, such as " if (someotherscript.getcomponent().somebool)" but i want to make it reusable with other scripts and their fields. as in, assigning them in the inspector
this is basically what i want, is there some (somewhat simple) way to make this or something similar?

By ‘script in the project’, do you mean the script file itself or the Type the file represents in the compiled project? Or a monobehaviour or other asset in the scene/project files?

The .cs files themselves aren’t proper assets, ergo, they don’t ‘exist’ at run time. You can retrieve the existing System.Type’s in the project with UnityEditor.TypeCache, but to actually serialise the reference to the type will require custom serialisation.

Getting references to assets or objects in the scene is easier, which can be done with UnityEditor.AssetDatabase or FindAllObjectsOfType, and serialising these is of course supported natively.

As for checking certain fields, that is akin to what the in built UnityEvent does, which I believe works via reflection. Not sure how these are serialised honestly.

All the above will require lots of custom editor work too.

What’s your end goal here? Is this something you can do via interfaces perhaps?

At the risk of buying a drunk a drink:

Your first field, referencing the script instance itself, you don’t need to do anything special. Use

public Component targetComponent;

You can now drag any component from any GameObject into that field.

From there, use this:

Edit: To clarify my initial comment: this idea fills me with anxiety. Anonymously and remotely monitoring the internals of other components in a way that isn’t even inspectable or searchable in code?

1 Like

a monobehavior on the project.
im making a behavior tree, and i want to make a “condition” node, for example to check the variable “speed” on a component in a certain object in the scene. but i also want that condition node to work with other objects’s components and their fields.

i get this, but i cant think of a better solution for what i need.
i want my contion node to check on the fields of the blackboard (lower left) but i dont want it to be hardcoded, since i would need a lot of “condition nodes”

There’s a GetComponent that allows you to pass the type as a parameter. Any reason you are not using that one?