Search Unity

Question Accessing script variable by name

Discussion in 'Getting Started' started by VterHorst, Apr 22, 2023.

  1. VterHorst

    VterHorst

    Joined:
    Aug 1, 2017
    Posts:
    1
    Hi everyone,

    I'm trying to access a variable in a script that is added during runtime.

    Code (CSharp):
    1.        
    2.         EventName = "Event_Bandits_01";
    3.         gameObject.AddComponent(Type.GetType(EventName));
    4.  
    5.         Title = GetComponent<Event_Bandits_01>().Title;
    6.         Title = GetComponent<EventName>().Title;
    7.  
    The code above works as long as the name in GetComponent is a set name(line 5), I can't get it to work if I use a string to look up the script(Line 6). Any idea what I can do to access the script?

    Thanks!
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    5,043
    Maybe use enums or dictionaries to make this easier?