Unexpected increase in List.Count after adding elements to the list

76 Views Asked by At

After running the following loop (one iteration), battleshipParts.Count returns 2.

The code is ran once in the ScriptableObject.Awake

for (byte i = 0; i < 1; i++)
{
    var battleshipPart = CreateInstance<BattleshipPart>();
    battleshipPart.battleshipData = this;
    battleshipParts.Add(battleshipPart);
}

I tried using the debugger and walking through the code, after the execution of

battleshipPart.battleshipData = this;

battleshipParts.Count is already 1

battleshipPart.battleshipData is used to hold a reference to its battleship parent. Implementation:

public class BattleshipPart : ScriptableObject
{
    public Vector2 gridPosition;
    public BattleshipData battleshipData;
    public bool isHit = false;
}

The battleshipParts list isn't modified anywhere else besides this code. Besides. Why would it update itself with a null value after running battleshipPart.battleshipData = this;?

1

There are 1 best solutions below

0
Dellivi On

This error because you create Instance not Asset and trying to save it into list.

Just create .asset(ScriptableObject) file with AssetDatabase in project.

    for (byte i = 0; i < 1; i++)
    {
        BattleshipPart battleshipPart = ScriptableObject.CreateInstance<BattleshipPart>();
        AssetDatabase.CreateAsset(battleshipPart, $"Assets/BattleshipPart_{i}.asset");
        AssetDatabase.SaveAssets();

        battleshipPart.battleshipData = this;
        battleshipParts.Add(battleshipPart);
    }

If you don't want to create asset file in your project, just use simple serialized class not ScriptableObject.