简体   繁体   English

Unity中的UI按钮是否有位置?

[英]Does a UI Button in Unity have a location?

I wanted to make a game where you click a button and it affects another button. 我想制作一个游戏,您单击一个按钮,它会影响另一个按钮。 I made a grid. 我做了一个网格。 If I click a button in this grid I want to have it affect another button's image. 如果单击此网格中的一个按钮,则希望它影响另一个按钮的图像。 However I need some sort identifier which tells me which button is which. 但是,我需要一些排序标识符来告诉我哪个按钮是哪个按钮。

在此处输入图片说明

I'm used prefabs for a button, then made a 5x10 grid prefab of those prefabs. 我将预制件用作按钮,然后将这些预制件制成5x10网格的预制件。 Any guidance towards the right direction would be helpful even if it does not answer the question thank you. 即使没有正确回答谢谢您,任何朝着正确方向的指导也将有所帮助。

This can be done easily 这很容易做到

First lets make a script GridController.cs 首先让我们编写一个脚本GridController.cs

Add a reference to the UI namespace at the top using UnityEngine.UI; using UnityEngine.UI;在顶部添加对UI名称空间的引用using UnityEngine.UI;

Now place all of your grid items in a parent container(can be an empty gameobject) 现在将所有网格项放置在父容器中(可以是一个空的游戏对象)

Now lets start coding 现在开始编码

//Reference parent gameobject
[SerializeField]
private GameObject gridContainer;

//List of all child elements
private List<Button> gridObjects = new List<Button>();

private void Start(){
  //Loop through all children
  for(int i = 0; i < gridContainer.transform.childCount; i++){
    //Add button to list
    gridObjects.Add(gridContainer.transform.getChild(i).gameObject.GetComponent<Button>());
  }

  //Set listeners for buttons

  for(int i = 0; i < gridObjects.Count;i++){
    gridObjects[i].onClick.AddListener(delegate{
      DoSomething();
    });
  }
}

private void DoSomething(){
  //Do Something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM