Forum rules - please read before posting.

Action to Find a gameObject and a component to enable/disable it

Hi, with the help of ChatGPT I managed to get this action that can find a gameObject in the scene (by its name) and a component attached to it (also by its name) to enable or disable it.

When there are multiple gameObjects with the same name in the scene, the script will stop at the first instance it finds.

Add it to your custom actions folder to the Custom actions in the AC window.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace AC
{

    [System.Serializable]
    public class ActionFindObjectAndToggleComponent : Action
    {
        public string objectName = "";
        public string componentName = "";
        public bool setActive = true;

        public ActionFindObjectAndToggleComponent ()
        {
            isDisplayed = true;
            category = ActionCategory.Custom;
            title = "Find Game Object Component";
            description = "Find a gameObject in the scene and enable or disable the component attached.";
        }

        public override float Run()
        {
            GameObject obj = GameObject.Find(objectName);

            if (obj != null)
            {
                Component comp = obj.GetComponent(componentName);

                if (comp != null)
                {
                    if (comp is Behaviour behaviour)
                    {
                        behaviour.enabled = setActive;
                    }
                    else if (comp is Collider collider)
                    {
                        collider.enabled = setActive;
                    }
                }
                else
                {
                    ACDebug.LogWarning("Component " + componentName + " not found on " + objectName);
                }
            }
            else
            {
                ACDebug.LogWarning("GameObject " + objectName + " not found in scene");
            }

            return 0f;
        }

#if UNITY_EDITOR
        public override void ShowGUI()
        {
            objectName = EditorGUILayout.TextField("Object Name:", objectName);
            componentName = EditorGUILayout.TextField("Component Name:", componentName);
            setActive = EditorGUILayout.Toggle("Set Active:", setActive);

            AfterRunningOption();
        }
#endif
    }

}
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Welcome to the official forum for Adventure Creator.