Search Unity

Question Get the type of a scipt to use it in GetComponent<scr>()

Discussion in 'Scripting' started by Saw9yer, Jan 4, 2022.

  1. Saw9yer

    Saw9yer

    Joined:
    Sep 19, 2020
    Posts:
    72
    Hello everyone,
    I have a gameobejct with a script.
    I want to find the type/name og the script in order to use it in GetComponent<script>()

    I tried many solutions and i can find the name of my script using one of these lines :
    Code (CSharp):
    1.  
    2.         MonoBehaviour script = activator.GetComponent<MonoBehaviour>(); //return the correct name
    3.         Type script = activator.GetType();//return the correct name
    4.      
    5.  
    However i can't find a way to use my script for exemple :
    Code (CSharp):
    1.     bool CheckIfActivatorActive()
    2.     {
    3.    
    4.         Type script = activator.GetType();//return the correct name
    5.         if (activator.GetComponent<script>().active == true)
    6.          {
    7.              return true;
    8.          }
    9.          else return false;
    10.  
    11.     }
    This code return an error "script is a variable but used like a type".

    Can you help me?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,740
    You can't use the Generic <T> version this way. I believe that's because those are compile-time determined.

    GetComponent() has an overload that takes a System.Type argument. Use that instead.
     
  3. Saw9yer

    Saw9yer

    Joined:
    Sep 19, 2020
    Posts:
    72
    I think i miss something it don't works for me.
     
  4. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
  5. Saw9yer

    Saw9yer

    Joined:
    Sep 19, 2020
    Posts:
    72
    I also tried to use a string without sucess :(
    Code (CSharp):
    1.         MonoBehaviour script = activator.GetComponent<MonoBehaviour>();
    2.         string str = script.ToString();//the string is correct
    3.         MonoBehaviour scr = activator.GetComponent(str) as MonoBehaviour;//return null
    4.         Debug.Log(scr.active);//CS1061
     
  6. Saw9yer

    Saw9yer

    Joined:
    Sep 19, 2020
    Posts:
    72
    For now the best i did is the code below.
    Code (CSharp):
    1.         MonoBehaviour script = activator.GetComponent<MonoBehaviour>();
    2.         string str = script.GetType().Name;
    3.         var otherScript = activator.GetComponent(str);
    4.         Debug.Log(otherScript);//return the correct name
    5.         Debug.Log(otherScript.active);//CS1061
     
  7. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,925
    In your initial post, why do you need to get the type of something you already have a reference to and then GetComponent it again?

    What are you actually trying to achieve here?