button.onClick.AddListener in for loop

I need to add button with onclick event but I cant

for (int i = 0; i < 10; i++)
{
var obj = new GameObject();
obj.AddComponent<Button>();
obj.GetComponent<Button>().onClick.AddListener(() => somefunc(i));
}

problem is after Start() ends, i is setting to null and when I click on button it raises ArgumentOutOfRangeException. How can I solve this problem?

Note: All code :

    void Start () {
        player = GlobalVariables.player;

        for (int i = 0; i < player.items.Count; i++)
        {
            var obj = new GameObject();
            obj.AddComponent<Image>();
            Image image = obj.GetComponent<Image>();
            image.sprite = Resources.Load <Sprite>(player.items*.slug.ToString());*

var wear = new GameObject();
wear.AddComponent();
wear.AddComponent();
wear.AddComponent();
wear.GetComponent().sprite = Resources.Load(“UISprite”);
wear.GetComponent().transform.localScale = new Vector3(0.1f, 0.1f, wear.GetComponent().transform.localScale.z);
wear.GetComponent().onClick.AddListener(() => player.wearItem(player.items*));*

wear.transform.SetParent(obj.transform);
obj.transform.SetParent(inventory);

}
}

I don’t know why, but i have the same problem

obj.GetComponent<Button>().onClick.AddListener(() => somefunc(i));

try

int x = i;
obj.GetComponent<Button>().onClick.AddListener(() => somefunc(x));

It is due to the closures
simply use a copy variable, and it’s done.

 for (int i = 0; i < 10; i++)
 {
    int copy = i;
    var obj = new GameObject();
    obj.AddComponent<Button>();
    obj.GetComponent<Button>().onClick.AddListener(() => somefunc(copy));
 }