Search code examples
c#unity-game-engine

Unity GetComponent(string Script)


I need to get component from object by string variable. How can i do it?

Here is my current code:

Canvas.GetComponent<Global_Variables>().Active_Figure.GetComponent(Script_Name).Cancel();

But I get the following error in the console :

Assets/Scripts/Cell.cs(62,20): error CS1061: Type UnityEngine.Component' does not contain a definition for Cancel' and no extension method Cancel' of type UnityEngine.Component'


Solution

  • You have to cast the result returned by GetComponent().

    I will assume that the Cancel function is defined in a class (or interface) called Cancelable your script are inheriting from (or implementing).

    Cancelable myScript = Canvas.GetComponent<Global_Variables>().Active_Figure.GetComponent(scriptName) as Cancelable;
    myScript.Cancel();
    

    EDIT :

    Next time, don't forget to post your code correctly formatted, and to put any additional information which could help how to resolve your problem (such as the error the console gives you)