- Home /
How can i create nested-menu with c# script?
i want creat nested menu with script but i have some problem.
List mButton = new List();
public RectTransform buttonRect;
public bool open;
public int buttonDistance ;
Vector2[] buttonPos;
float speed = 10.0f;
float buttonHeight;
void Start () {
buttonHeight = buttonRect.rect.height*2.0f;
mButton = this.GetComponentsInChildren<Button>(true).
Where(x => x.gameObject.transform.parent != transform.parent).ToList();
buttonPos = new Vector2[mButton.Count];
this.GetComponent<Button>().onClick.AddListener( () => { OpenMenu();} );
this.GetComponent<RectTransform>().pivot = new Vector2(1f, 1f);
foreach (Button b in mButton)
{
b.gameObject.SetActive(false);
}
}
public void OpenMenu()
{
open = !open;
for(int i =0;i<mButton.Count;i++)
{
if(open)
{
float xpos = buttonRect.rect.width*1.5f;
float ypos = (i+1)*buttonHeight;
buttonPos[i] = new Vector2(this.transform.position.x + xpos, this.transform.position.y + ypos);
}
else
{
buttonPos[i] = this.transform.position;
}
}
StartCoroutine(MoveElements());
}
private IEnumerator MoveElements()
{
foreach(Button b in mButton)
{
b.gameObject.SetActive(true);
}
int loops = 0;
while(loops<= buttonDistance / speed)
{
yield return new WaitForSeconds(0.01f);
for(int i = 0; i < mButton.Count; i++)
{
Color c = mButton[i].gameObject.GetComponent<Image>().color;
if (open)
c.a = Mathf.Lerp(c.a, 1, speed * Time.fixedTime);
else
c.a = Mathf.Lerp(c.a, 0, speed * Time.fixedTime);
mButton[i].gameObject.GetComponent<Image>().color = c;
mButton[i].gameObject.transform.position = Vector2.Lerp(mButton[i].gameObject.transform.position, buttonPos[i], speed * Time.fixedTime);
}
loops++;
}
if (!open)
{
foreach(Button b in mButton)
{
b.gameObject.SetActive(false);
}
}
}
What do you want achieve exactly, how do you want to position the buttons? If I understand correctly, you want them to be children of this game object, arranged vertically. Have you considered using a VerticalLayoutGroup
?
I want create nested for multi-resolution and buttons don't separate.
Yeah use that, vertical layout, even you can create an Scroll view so you can see your buttons in a scroll list. To make a layout group, your buttons shall have layout element.
Your answer
Follow this Question
Related Questions
Good idea to use nested canvases for children of scrollable lists? 2 Answers
Converting UI RectTransform to Screen Pixel and vice-versa 5 Answers
how to move child object inside a moving parent in 2d using Vector2.MoveTowards()? 1 Answer
Make healthbar size from percentage instead of value. 2 Answers
How do i make my ui elements stay the same size and position on all andorid devices? 1 Answer