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): public Text text; public int indentLevel = 4; [SerializeField] private bool applyTypewriter = false; [MenuItem("Window/Text FX")] public static void CreateWizard() { EditorWindow.GetWindow(typeof(TextWizard)); } private void OnGUI() { EditorGUI.BeginChangeCheck(); EditorGUILayout.Space(); (Canvas)EditorGUILayout.ObjectField("Canvas", canvas, typeof(Canvas), true); EditorGUILayout.Space(); text = (Text)EditorGUILayout.ObjectField("Text", text, typeof(Text), true); EditorGUILayout.Space(); applyTypewriter = EditorGUILayout.ToggleLeft("Apply typewriter", applyTypewriter); if (applyTypewriter == true) { text.AddComponent("TypewriterEffect"); //error starts here }
You add components to GameObjects, not Components to Components. Try: Code (CSharp): 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
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.