Search Unity

Resolved How to match type of script

Discussion in 'Scripting' started by ThreadAndSandpaper, Feb 20, 2024.

  1. ThreadAndSandpaper


    Apr 1, 2023
    I want to be able to feed in a script and a game object into a method, then have the method find and cache a reference to a component on the game object that matches the type of the given script.

    (goodness I hope I've used the right words, I'm still a baby programmer)

    Any way this is what I have:

    Code (CSharp):
    1. public Component thingToMatch;
    3. public void ResolveActivity(GameObject character)
    4. {
    5.     Type typeToMatch = thingToMatch.GetType();
    6.     Component componentToCache = character.GetComponentInChildren<typeToMatch>();
    9. }
    it objects to the last 'type to match' with: 'typeToMatch' is a variable but is used like a type. Can someone point me in the right direction?

    PS: if it helps the goal here is to create a set of scriptable objects where I can point to one of a many scripts on a game object. Each script will only exist once, and (at the moment) all the classes I'm trying grab are child classes of the same parent.
  2. spiney199


    Feb 11, 2021
    You have marked your thread as resolved but haven't written what your solution was. Have you solved your problem? If so, it would help future readers to know what you did.