0
public Button Button1;
public class ButtonControl : MonoBehaviour
{
    public Button Button1;//ссылка на мой prefab
    public Button[,] arrayButtons = new Button[4, 4];

    void Start()
    { 
        arrayButtons[0, 0] = Button1;

        Instantiate(arrayButtons[0, 0],transform.position ,Quaternion.identity);

        Button1.onClick.AddListener(TaskOnClick1);


    }
0

1 ответ 1

0
        public GameObject btnPrefab;
        public GameObject btnGenerator; // тут канвас или что угодно(ui,пустой объект),
                                        //это родительский объект
        void Start(){
                    GameObject tempButtonObj = Instantiate(btnPrefab, btnGenerator.transform) as GameObject;
                    Button tempButton = tempButtonObj.GetComponent<Button>();
                    tempButton.onClick.AddListener(() => TaskOnClick1()); 
        }


void TaskOnClick1(){
//ваш код
}

Случай,когда надо много заспавнить

Button[] buttons = new Button[10]; // допустим 10

        for (int i = 0; i < 10; i++)
        {

            GameObject tempButtonObj = Instantiate(btnPrefab, btnGenerator.transform) as GameObject;
            Button tempButton = tempButtonObj.GetComponent<Button>();

            buttons[i] = tempButton;
            int tempIndex = i;

            buttons[i].onClick.AddListener(() => TaskOnClick1());
        }
1
  • 1
    Я добавлю, что приведение типа as GameObject здесь избыточно, потому что Instantiate<T> уже возвращает T. Также чаще всего приходится добавлять false третьим параметром, чтобы локальный масштаб элемента остался такой же как в префабе. 31 мая 2019 в 6:35

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.