- Home /
Check if game object is active in hierarchy from a prefab
If I want to check if game object is active I know I can use if(GameObject.ActiveInHierarchy){...} But what I want to do now is check that from a prefab. I obviously can´t just drag and drop a game object into a prefab.. so what do I do? I did already try to use..
FallOrFly = GameObject.FindGameObjectWithTag("FallOrFly");
if (FallOrFly.activeInHierarchy == true)
{....}
But it doesn´t seem to work?
Thanks.
GameObject FallOrFly; public bool activeSelf; public int score;
void SomeFunction() {
if (FallOrFly == null)
FallOrFly = GameObject.FindGameObjectWithTag("FallOrFly");
if (FallOrFly.activeSelf == true)
{
...
}
}
Answer by Borr1310 · Nov 03, 2016 at 12:57 PM
FIXED IT!
I am sorry for not giving you all the information. The problem was that the prefab can´t detect inactive game objects so it returned null every time the game object was set to false. My way around it was to ad:
if (FallOrFly == null)
{
}
if (FallOrFly != null)
{
if (FallOrFly.activeInHierarchy == true)
{
}
}
Thank you for all responses.
Answer by Cynikal · Nov 03, 2016 at 11:28 AM
Your code should work just fine on your prefab. But, let's break it down Barney Style.
You're using: FindGameObjectWithTag. Are you sure it's TAGGED as such and not Named?
Are you sure the object is instantiated?
Where are you initiating this Find at? On the instantiated prefab? And if so where? In Start?
Alright... First off let me try to explain what I´m trying to do. I have 2 "Game modes". Flying and Falling. The default game mode was flying and then I decided to add another one so the game is not that boring.. So I created an empty game object named FallOrFly. Then I have 2 buttons Fall or Fly. If you press fall everything is the same except that FallOrFly gameobject is set to inactive. Then I added an if statement in front of almost every "function" ( if FallOrFly is set to active(he pressed fly) so do everything in fly mode and if ForOrFly is set to inactive that means the user pressed fall so do everything in fall mode.. Now the only problem I am having is that I can´t add that if statement since I don´t know how to get ForOrFly gameobjects status from a prefab. And that prefab is a parent of the whole obstacle thing(2cubes,emptyspace,coins...) It is being instantiated with InvokeRepeating.
$$anonymous$$y game object is tagged "FallOrFly" and I am trying to find an object with tag(FallOrFly)..
The object I believe is instantiated.. ? The script is attached to the parent and the parent is being instantiated with Invoke Repeating so I believe it is instantiated..
I am calling
FallOrFly = GameObject.FindGameObjectWithTag("FallOrFly");
in Start() on the script attached to the parent GameObject.
Also I am getting that error: Object reference not set to an instance of an object, I believe that means that the instantiated prefab cant find the gameobject...