Search Unity

AddComponent to a Text UI?

Discussion in 'Scripting' started by neohazardous, Jun 13, 2018.

  1. neohazardous

    neohazardous

    Joined:
    Oct 16, 2017
    Posts:
    3
    Hey there! So I'm creating a custom editor window. I want the user to be able to attach different scripts to a text object through toggle options. For example, toggle to apply/remove a typewriter script to the UI text. However, I'm getting errors back whenever I tried to use .AddComponent"ScriptName"). I've tried to figure out different ways to add the script component to the UI text, but haven't had any real results. Could someone please tell me if I'm going about this entirely wrong or if Im just making a mistake?

    Code (CSharp):
    1.  public Text text;
    2.  
    3.     public int indentLevel = 4;
    4.    [SerializeField]
    5.     private bool applyTypewriter = false;
    6.  
    7.    
    8.     [MenuItem("Window/Text FX")]
    9.     public static void CreateWizard()
    10.     {
    11.         EditorWindow.GetWindow(typeof(TextWizard));      
    12.     }
    13.  
    14.     private void OnGUI()
    15.     {    
    16.         EditorGUI.BeginChangeCheck();
    17.         EditorGUILayout.Space();
    18.  
    19. (Canvas)EditorGUILayout.ObjectField("Canvas", canvas, typeof(Canvas), true);
    20.         EditorGUILayout.Space();
    21.         text = (Text)EditorGUILayout.ObjectField("Text", text, typeof(Text), true);
    22.         EditorGUILayout.Space();
    23.  
    24.  
    25.         applyTypewriter = EditorGUILayout.ToggleLeft("Apply typewriter", applyTypewriter);
    26.         if (applyTypewriter == true)
    27.         {
    28.            
    29.             text.AddComponent("TypewriterEffect"); //error starts here
    30.  
    31.        
    32.         }
     
  2. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
    You add components to GameObjects, not Components to Components.
    Try:

    Code (CSharp):
    1. text.gameObject.AddComponent("Something");
    Also, you didnt bother showing us the error. That is a vital thing to do as it tells you what is wrong.

    Also, I think that will trigger every single time the UI updates while the toggle is true, I am sure you may experience this when it happens ;)
     
  3. neohazardous

    neohazardous

    Joined:
    Oct 16, 2017
    Posts:
    3
    Your suggestion actually worked out perfectly! And yeah, I caught on to the infinite add on of components while the toggle is true. I added an if statement to check for pre-existing components to make sure it doesn't keep adding more.
     
    TaleOf4Gamers likes this.