Add listener on Objects that are part of dictionary
void ConfigButtonListeners()
{
buttonKeyTypes[Profile.keyType.LEFT] = buttonKeyLeft;
buttonKeyTypes[Profile.keyType.RIGHT] = buttonKeyRight;
buttonKeyTypes[Profile.keyType.JUMP] = buttonKeyJump;
buttonKeyTypes[Profile.keyType.SHOT] = buttonKeyShot;
buttonKeyTypes[Profile.keyType.PICKUP] = buttonKeyPickup;
foreach(KeyValuePair<Profile.keyType,GameObject> pair in buttonKeyTypes) {
Button button = pair.Value.GetComponent<Button>();
Debug.Log(pair.Key); //gives right value
button.onClick.AddListener(
delegate {
isConfiguring = true;
Debug.Log(pair.Key); //gives wrongvalue
configButtonPointer = pair.Value;
});
}
}
Inserting all public GameObjects in dictionary (works correctly, I checked the values)
For each dictionary value(GameObject) I'm getting it's Button component
I'm defining what will happen onClick on every of those buttons over delegates (Problem is here somewhere)
When I click on one of those buttons 'configButtonPointer ' will refrence to that object that was clicked
The problem is that 'configButtonPointer' is always refrencing last value(GameObject) in dictionary which is buttonKeyPickup, instead of being refrence to a GameObject that holds button that was last pressed. I hope you understand what I was trying to say and thanks in advance.
Answer by DrunkBearzz · Sep 20, 2016 at 09:31 AM
UPDATE
I changed configButtonPointer = pair.Value;
to configButtonPointer = button.transform.gameObject.transform.parent.gameObject;
and now it works. I guess it has something to do with a scope of delegate but if anyone knows why it didn't work before, explanation would be nice.
Your answer
![](https://koobas.hobune.stream/wayback/20220612093133im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Getting "object reference not set" error when creating a list dictionary. 1 Answer
How to create a turn based system manager? 0 Answers
Enemy Database using list/dictionary to store stats (C#)? 1 Answer
Insert string into empty list at a specific index 0 Answers
Need help to generate a random assortment of 4 buttons - C# 0 Answers