Introduction
In this article we are going to see how to know the state of any GameObject through code in Unity.
The GameObjects are the elements of the scene that are used to model everything that exists in our project in Unity. One of the basic properties that these GameObjects have is their activation state, in the inspector window can be seen as a checkbox that when checked the GameObject is ACTIVE and if the checkbox is unchecked the GameObject is INACTIVE.
All the IMPORTANT information is summarized in the following TUTORIAL FROM MY YOUTUBE CHANNEL
Procedure to know if a GameObject is ACTIVE or INACTIVE in the scene
Let’s assume that there is already a script created and assigned to a GameObject in Unity so that its instructions can be executed.
Step 1 – Define REFERENCE
To solve practically any problem in Unity we have to start with the variables that we are going to use, in this case we need to have the reference of the GameObject that we want to analyze, in other words, in our script we will define a global variable of type GameObject, for example in the following way:
public GameObject myGameObject
Step 2 – Initialize REFERENCE
The variable we defined in the previous step will not automatically point to the GameObject we are interested in knowing if it is ACTIVE or INACTIVE in the scene, we have to make sure that happens.
There are several ways to initialize a variable, click here to see a playlist with several videos where you can see methods and examples on this topic, in this case we are going to go to the inspector where we have the script assigned and we are going to drag manually the GameObject that we are interested in analyzing to the GameObject type variable that appears in the inspector, in our case it is called “myGameObject”. This way now that variable will point to the GameObject that we are interested in.
Step 3 – How to READ the GameObject status
Having solved the previous two steps we can now use the variable we defined to know if the GameObject is ACTIVE or INACTIVE in the scene. For this we use the following instruction.
myGameObject.activeInHierarchy
The previous instruction is equivalent to a boolean value, if the GameObject to which the variable “myGameObject” is pointing is active in the scene the expression will give as result “true”, while if it is inactive it will give as result “false”. Therefore we can use this expression to do whatever we want, for example define an IF statement and print a message in console if the object is active and a different message if it is inactive, for example:
if(myGameObject.activeInHierarchy){
Debug.Log(“The GameObject is ACTIVE”);
}else{
Debug.Log(“The GameObject is INACTIVE”);
}