Why Unity Freezes when i set parent to an Instantiated GameObject?

,using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PickupWeapon : MonoBehaviour {

public GameObject weaponToBuy;

private void OnTriggerStay2D(Collider2D other)
{
    if (other.gameObject.tag == "Player")
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            
            foreach (Transform weapon in other.transform)
            {
                
                if (weapon.gameObject.activeSelf)
                {
                   
                    GameObject newWeapon = Instantiate(weaponToBuy, new Vector2(other.transform.position.x, other.transform.position.y), Quaternion.identity) ;
                   
                    newWeapon.transform.parent=other.transform;
                }
            }
        }
    }

}

}

I Debugged the script and it works perfectly without the parent line. Unity freezes when i press f on the collider and i have to force shut down it.

You have a set of weapons as children to the Player when the foreach loop starts. Then when you Instantiate each new weapon and parent it to the Player, the original list of children of the Player changes, and this, apparently, messes up the foreach loop.

Generally, it’s not good to alter the original collection, with which the foreach loop is operating on.

Maybe you should just add your newly instantiated weapons to, say, a List<Transform> newWeapons, and after the foreach loop finishes, do the parenting to the Player (and then clearing the newWeapons List.

Thank you for helping !
I took the parent line out of the foreach loop and i works wonders.