top of page

008-Custom Editor referencing gameObject

1.1 Introduction

1. In this tutorial we are going to learn how to reference to the gameObject for which the custom editor is built. This allows us to perform operations on the object for which the editor is built.

2. Open the 008 folder in the project to access the files.

1.2 Basic Script

1. Let us open the Test008 script and look at its content.

image.png
image.png
1.2 Adding a custom inspector

1. Let us make a script called as Test008Editor.cs that we will use as custom editor for Test008.

2. To use this as custom editor:

a. Make it inherit from Editor class in UnityEditor namespace.

b. Use a CustomEditor attribute with the type for which this is a custom editor

c. Override the default GUI function to write our own functionality.

base.OnInspectorGUI() tells the unity to draw the default test006 editor.

image.png
1.3 Adding buttons

1. To this CustomEditor let us add two buttons "Add Rigidbody" and "RemoveRigidbody"

​

image.png
image.png

Currently these two buttons perform no action

1.3 Accessing gameObject

1. target field holds the reference to the script for which editor is built.

2. Let us access the target field and print the name of the current gameObject first to understand how it works.

image.png

3. First we cast the target as the type for which editor is being built for.After that we are able to access the name of the gameObject to which the script is attached.

image.png
image.png

4. Finally we are able to print the name of the gameObject using button.

1.3 Adding and Removing Rigidbody

1. As we are now able to access the current gameObject for which the custom editor is built let us add the functionality to add or remove rigidbody

2. First we get access to the target using which we are able to gain access of the gameObject.

3. After that we will add and remove rigidbodies.

image.png

1. As we are now able to access the current gameObject for which the custom editor is built let us add the functionality to add or remove rigidbody

2. First we get access to the target using which we are able to gain access of the gameObject.

3. After that we will add and remove rigidbodies.

image.png
image.png
image.png

First

Second-After pressing "AddRigidbody"

Third-After pressing "RemoveRigidbody"

End

Kindly support me through my Patreon account if you find these tutorials useful. Feel free to connect with me on Twitter. This support enables me to create more educational content.

bottom of page