Me again with the same question. I spent couple of hours trying now and I could not find a solution for this problem. I will try to give as much information as possible.
using JetBrains.Annotations;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class Shop : MonoBehaviour
{
[Header("List of items sold")]
[SerializeField] private ShopItem[] shopItems;
[Header("References")]
[SerializeField] private Transform shopContainer;
[SerializeField] private GameObject shopItemPrefab;
List<GameObject> itemList = new List<GameObject>();
public void Start()
{
PopulateShop();
}
private void PopulateShop()
{
for (int i = 0; i < shopItems.Length; i++)
{
ShopItem si = shopItems[i];
GameObject item = Instantiate(shopItemPrefab, shopContainer) as GameObject;
//grab buttons to make listeners on them
//buy button
item.GetComponentsInChildren<Transform>(true).FirstOrDefault(t => t.name == "buyButton").GetComponent<Button>().onClick.AddListener(() => buyButtonClick(si));
//info button
item.transform.Find("infoButton").GetComponent<Button>().onClick.AddListener(() => infoButtonClick(item));
//infoReturnButton
item.transform.GetChild(5).GetChild(1).GetChild(1).GetComponent<Button>().onClick.AddListener(() => infoCancelButtonClick(item));
//change prefabs values
item.transform.name = si.name;
item.transform.GetChild(4).GetComponent<Image>().sprite = si.sprite;
item.transform.GetChild(3).GetComponent<Text>().text = si.price.ToString();
item.transform.GetChild(5).GetChild(1).GetChild(0).GetComponent<Text>().text = si.infoText;
itemList.Add(item);
}
}
public void infoButtonClick(GameObject item)
{
GameObject currentInfo =item.transform.GetComponentsInChildren<Transform>(true).FirstOrDefault(t => t.name == "infoBackgroundImg").gameObject;
currentInfo.SetActive(true);
}
public void buyButtonClick(ShopItem item)
{
Debug.Log("aki ist gay");
}
public void infoCancelButtonClick(GameObject item)
{
GameObject currentInfo = item.transform.GetComponentsInChildren<Transform>(true).FirstOrDefault(t => t.name == "infoBackgroundImg").gameObject;
currentInfo.SetActive(false);
}
}
I am creating objects of one Prefab. The Prefabs structure is the following:
And I have a ShopItem which gives some values inserted into the Prefab looking like this:
Right now there are a total of 3 objects being created and all of this works just fine. the Problem is now that only the buttons of the last created object work. Let me show you my event system:
This is Object3(the last one). As you can see the pointerpress works (buyButton). If we now go to f.e. object2 you can see that it does not even recognize that the button is there.
But when looking at the objects you can see that the button is there.
So I do not understand why the button only works for Obj 3 when Obj 1&2 also have the button and when I delete Obj 3 the buttons of Obj 2 start working.
I have no clue any more why it is not working.
edit