Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Bug List.Add(item) not working after object being disabled and enabled again

Discussion in 'Scripting' started by eduardoromeueberts, Mar 26, 2024.

  1. eduardoromeueberts


    May 8, 2023
    I have a script that uses a bunch of lists to store lists of ScritableObjects:
    Code (CSharp):
    1.     private List<VehiclePartData> _changedAdjusts = new();
    2.     private List<VehiclePartData> _selectedParts = new();
    3.     private List<VehiclePartData> _partsToInstall = new();
    4.     private List<VehiclePartData> _partsToUnninstall = new();
    when I want to add an item to one list, varying on the logic of what list to use, it will be like this:
    Code (CSharp):
    1. if (!_selectedParts.Contains(part))
    2. {
    3.        _selectedParts.Add(part);
    4.        Debug.Log($"Selecting part
    5. {part.LocalizedName.GetLocalizedString() ?? part.Name}");
    6. }
    The object that holds these lists is part of a scene that's loaded additively and then unloaded when player exits, so the object is disabled together. On the first time that this scene is loaded, the code above works as expected, and the part is added to the list:

    But when we exit the scene and enter again, the debug.log shows but the part is no longer added to the list:

    I tried many things like clearing or initializing the list on Start and OnEnable but nothing fixes this, and I have no other clue of the reason for this to be happening.
  2. Bunny83


    Oct 18, 2010
    You've shown only minimal context of your code. You said those lists are part of a "script". So we would assume that this script is actually a MonoBehaviour component on an object in that scene you were talking about? So you are 100% sure that the object is actually destroyed and recreated? You checked this with Awake / OnDestroy? If the object is not destroyed, the added part would still be inside the list. Have you checked that the list is actually empty? Have you checked what the "Contains" call actually returns by adding an else statement with another Debug.Log?

    Your external images do not work. Next time embed the images in your post. External images are never a good idea as they can always become dead links which may render the question useless.