1

I am creating an editor script for a certain type of component script, I'd like to access the specific component script referenced by that instance of the editor script. For example, target returns the game object the editor is attached to but I would like to get the actual script component inside it. The game object may have multiple components of this type and so needs to get the specific one.

[CustomEditor(typeof(CameraCutscene))] //Attaches to the CameraCutscene script
public class CutsceneEditor : Editor
{
    private CameraCutscene cameraCutscene;

    private void OnEnable()
    {
        Debug.Log(target.name);
        cameraCutscene = (CameraCutscene)target; //Attempt to cast to the script type but target returns the actual game object
    }
}

1 Answer 1

3

The target variable is a type of the UnityEditor.Object. To access component from the script attached to it, cast the UnityEditor.Object to MonoBehaviour and use the GetComponent function to get the component.

MonoBehaviour monoBev = (MonoBehaviour)target;
CameraCutscene cameraCutscene = monoBev.GetComponent<CameraCutscene>();

The game object may have multiple components of this type and so needs to get the specific one.

If you need to access multiple instance of the CameraCutscene script attached to the-same target then use GetComponents which returns array of the components attached to the target. Notice the 's' in it. Note that the in order which they are returned is not documented.

MonoBehaviour monoBev = (MonoBehaviour)target;
CameraCutscene []cameraCutscene = monoBev.GetComponents<CameraCutscene>();
Sign up to request clarification or add additional context in comments.

2 Comments

Just to clarify for future visitors, casting to MonoBehaviour and then getting the component worked, casting to GameObject did not.
@WillAnderson Used to work before. Modified answer to reflect that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.