Need Logic for hiding/ unhiding GameObjects (Collection of terrains) using Toggles in Unity

Viewed 32

I'm trying to hide/unhide A GameObject (Named "Ecosystem") comprising several children terrains using a Toggle switch for Unity. My bad, I tried setting Object as Active/ Inactive but to no avail. Please provide me with a feasible solution.

The pic of my idea I'm trying to implement. UI screenshot of the dilemma I'm facing; Unity Version 2020.1

2 Answers

The easiest way was to simply set Active the terrain as a whole object and then unchecking the Active checkbox at the topmost object. Then I implemented logic directly in Unity GUI under OnClick method boxes. This worked out for me.

Looks like your code is in the object that you trying to deactivate. Don't worry you don't have to move it to other GameObject. You could do that and turn it off (setActive(false)) from other object but if you don't want to do that here's what you can do.

You could get all the child objects of your ecosystem and turn them off one by one. Or just stop rendering them if you just want to hide (collision will still be on).

To do that we first start getting 0th element and turn it off. Then move up till we can't do more. I'm currently on my phone so my bad if something won't work or something. You haven't shared your code so I will just write my own Here's the code:

public GameObject tog;
public bool isonnow,isonprev;

void Update(){
isonnow=tog.GetComponent<Toggle>().isOn;
//If it was off in the last frame and is on now or vice versa
if (isonnow != isonprev){
int i=0;
while (true){
if (this.transform.GetChild(i)==null)break;
else
this.transform.GetChild(i).gameObject.SetActive(isnow);
i++;
}
}
//Save current state as previous for the next frame
isonprev=isonnow;
}

Hopefully I was helpful. Let me know if it works or not. Good luck

Related