K
K
kititnik12021-06-19 18:56:00
Unity
kititnik1, 2021-06-19 18:56:00

How to set UnityEvent in btn.AddListner()?

I have code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class Shop : MonoBehaviour
{
    public Items[] items;
    List<object> itemsList;
    [HideInInspector]public Items currentItem;
    public Main main;
    public GameObject item;

    private void Start()
    {
        itemsList = new List<object>(items);
        for (int i = 0; i < items.Length; i++)
        {
            currentItem = itemsList[i] as Items;
            GameObject p = Instantiate(item, shopPan.transform);
            p.transform.GetChild(0).GetChild(0).GetComponent<Text>().text = currentItem.name;
            p.transform.GetChild(0).GetChild(1).GetComponent<Text>().text = currentItem.cost.ToString();
            p.transform.GetChild(1).GetComponent<Image>().sprite = currentItem.Image;
            p.transform.GetChild(0).GetComponent<Button>().onClick.AddListener(currentItem.invokeMethod.Invoke);
        }
    }
}

[System.Serializable]
public class Items
{
    public int cost;
    public string name;
    public Sprite Image;
    public UnityEvent invokeMethod;
}

And this line just doesn't work:
p.transform.GetChild(0).GetComponent<Button>().onClick.AddListener(currentItem.invokeMethod.Invoke);

And I don't understand why. Found this article here: Link
But none of the suggestions helped. What to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2021-06-19
@freeExec

Make the argument AddListenera normal method, not what you wrote there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question