Problem with component

so I want to do an equip system in my game. I m using a PlayerManager to manage all stuff related to my player. The script is a bit long but this were I put gears the character is using. public Gear gear1 : Gear is a type that contains all my function and stats related to a gear.

In this exemple I m using the gear RepairKit

I use a button to equip it, and it calls the function equip of the repairKit :


player.gameObject.AddComponent<RepairKit>(); (edited)

player.gear1 = player.gameObject.GetComponent<RepairKit>(); (edited)

setRepairKit(level, player, position);

unequip is a function that destroy the current component (if it exits) at ‘position’ of the script ‘player’ (PlayerManager). Then I add the script RepairKit to my player object then I set this script to my player.gear1. Set RepairKit just all stuff related to Repair (its name, its desc, its level, etc)

There is no compilator error. When I equip once the gear there is no problem : everithing is fine but then when i try to reequip RepairKit evering works as well but the problem is in the inspector there is no stats and the third times I requip it the previous one is not deleted and the new is created with stats displayed in the inspector (the previous has still no stats) and the script still stacks like this when I reequip the RepairKit

I manage to some test to figure out why it isn t working but I just found despite the fact there is not stats display the gear is working proprely but gear1 is null (because it isn t destroyed the third time).

Why is this working this way ? (I want the second time I equip there is stats displayed like the first time)


Thanks for reading this and for you patience , I can show more code if you have some questions about it.

I found where the problem was. It is because when I invoke destroy() it takes place at end of my frame where I have 2 components RepairKit so it destroy the old and the new one is not initiate because the old one was initiate twice.

So I instead of using a destroy I use a destroyImmediate() and it worked as intended . Thx for your time @logicandchaos