- Home /
The question is answered, right answer was accepted
New GUI and Inventory problem.
Ok so basically what I have is an inventory with buttons representing objects and when you click on said button I need it to get said object so I can instantiate and do whatever else. However I am getting an argument out of range error after adding the listener to the GUI button.
I have only resently moved to the new GUI from unity 4.6 so I need help to figure it out all over again.
Here is the code that sets the listener to the GUI button in the inventory. It works as the debug registers but it won't assign the gameobject.
private GameObject eqObject; //the Object that is referenced;
for(int cnt = 0; cnt < plyrPlayerScript.CurrentInventoryList.Count; ++cnt){
//The button instantiated for each object.
GameObject slt = (GameObject)(Instantiate(ivntSlot));
slt.transform.parent = guiIvnt.transform.Find("MaskBox").transform;
//Set Onclick:
slt.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {
//Ok this works but you need graphics raycaster component on the parent of the buttons otherwise no click1!!!
Debug.Log("Works!!!!!!");
//This is the part that causes the out of range error. What am I not assigning or doing wrong?
eqObject = plyrPlayerScript.CurrentInventoryList[cnt].transform.gameObject;
});
//
}
//Thanks.
Answer by jenci1990 · Jun 28, 2015 at 02:58 PM
I think the problem is the delegate void. When you log 'works', please log the 'cnt' varible too. I think it is always count+1. Try make a new function to add listener to button. I think this will be solve your problem:
for(int cnt = 0; cnt < plyrPlayerScript.CurrentInventoryList.Count; ++cnt) {
GameObject slt = (GameObject)(Instantiate(ivntSlot));
slt.transform.parent = guiIvnt.transform.Find("MaskBox").transform;
AddButtonListener(slt, cnt);
}
void AddButtonListener(GameObject _slt, int _index) {
_slt.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {
eqObject = plyrPlayerScript.CurrentInventoryList[_index].transform.gameObject;
});
}
Awsome it works. Thanks bro.
Helped me understand a lot more of how the new GUI works.
Follow this Question
Related Questions
GUI.Button press (not click) 3 Answers
GUI Button to create another GUI 1 Answer
Stop clicking through a GUI window 2 Answers
Closing/hiding an open Gui Button when clicking on it 1 Answer
Instantiating object from inventory 0 Answers