SetActive(false) is preventing GameObjects from Instantiating
Hi,
I'm facing an issue where trying to hide a GameObject
with SetActive(false)
is preventing other GameObjects from instantiating. I've added some pseudocode below to illustrate my problem, basically I have a Cursor that can either select the player or open a menu, a Tilemap that can create new tiles (using a prefab) to show where the player can move, and a Menu that when clicked should select the player and then hide itself by deactivating.
As I'd expect, when I select the player the tiles all display correctly in the view as well as the hierarchy and the Log message also shows.
However, when I open the menu and click on it, the Log messages from the Tilemap will appear, showing that the tiles are being added, but no tiles appear either in the view or the hierarchy. If I remove the line gameobject.SetActive(false)
then the tiles render as expected but the UIMenu doesn't disappear.
The Tilemap and UIMenu objects are completely separate within the hierarchy so I find it very odd that one is affecting the other.
class Cursor {
public Tilemap tilemap;
public UIMenu uiMenu;
public void OnSelect(string selection) {
if (selection == "player") {
SelectPlayer();
} else if (selection == "menu") {
SelectMenu();
}
}
public void SelectPlayer() {
tilemap.ShowMovableTiles();
}
public void SelectMenu() {
uiMenu.Display(() => SelectPlayer())
}
}
class Tilemap {
public GameObject tile;
public void ShowMovableTiles() {
foreach(Transform position in SomeHowGetMovablePositions) {
Debug.Log("Adding new tile");
GameObject newTile = Instantiate(tile, position, Quaternion.identity);
newTile.gameObject.transform.SetParent(this.transform);
}
}
}
class UIMenu {
public Button button;
public System.Action action;
public void Awake() {
button = GetComponent<Button>();
button.AddListener(OnClick);
}
public void Display(System.Action onClickHandler) {
action = onClickHandler;
}
public void OnClick() {
action();
gameObject.SetActive(false); //hide menu
}
}
I've also tried logging appending newTile
to a public list and logging the length of the list as tiles are added. What's really weird is that the length of the list increases as expected but in the inspector the list remains unchanged. I'm really stumped, does anyone have an idea what's going on?
Answer by barney_unity869 · Nov 11, 2019 at 09:35 AM
I'm still not quite sure why this is happening, but I don't think it's related to the SetActive(false)
call. I updated the way I hide UI elements by adding a CanvasGroup
element and simply setting the alpha to 0 and turning off interactibility to make the UI gameobject disappear. Turns out that even doing this was preventing my gameobjects from instantiating.
I eventually solved the issue by hiding the UI on a time delay, Invoke("Hide", 0.01)
, feels a little hacky, but it works well!