How to close a menu by clicking a cloned button inside it?
I have a menu that gets populated at runtime with buttons whose text components are based on objects that the game manager has in its databases. At the start, the menu is empty:
![alt text][1]
See that "A" graphic? It's a button called Button_Magic_DropDown that activates/deactivates the panel called Panel_MagicMenu. At runtime, regardless of whether the panel is active, its child panel Empty_Inset_MagicMenu gets 6 children, which are all instances of the button prefab, Button_BattleMenu. When one of these buttons are clicked, I want the panel called Panel_MagicMenu to get deactivated. See image below:
![alt text][2]
What I am struggling with is deactivating [the parent panel of a ] panel that a button sits in when it is clicked. I am trying to do this by getting the second parent programmatically and deactivating it. Here is the script containing that function OnClickDeactivatePanel(), which I am assigning in the button prefab:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BattleUI : MonoBehaviour
{
public void ToggleActive(GameObject panel)
{
panel.SetActive(!panel.activeInHierarchy);
}
public void OnClickDeactivatePanel()
{
//On click, deactivates the panel that the button sits in, two parents up
GameObject secondParent = gameObject.transform.parent.parent.gameObject;
//Debug.Log("Second parent is " + secondParent);
secondParent.SetActive(false);
}
}
As you can guess, this didn't work. Unity is unable to identify the parents of an instanced object this way. I get a null-reference error. What can I do?
Answer by RickshawDerpyDerp · Oct 21, 2019 at 12:44 PM
I SOLVED IT, GLITCHES!
...thanks to helpful advice here.
Your answer
![](https://koobas.hobune.stream/wayback/20220612213700im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
HELP ME PLEASE TO FIX MY PROBLEM.. 1 Answer
How to change the position of a button? 1 Answer
Creating a 2D sprite with Trigger Events? 2 Answers
UGUI: Buttons on scrollview don't always register touches 1 Answer
Reference UI button in Script 1 Answer