Very Stuck With Adding New Variable To List

Godot Version

4.3

Question

In my game when the player adds a new object to the world there is a function that creates a variable that holds all the information about the object. For example, this variable gets the new objects name, ID number, and various other things. This variable is then added to a list of all the objects.

Some pseudocode:

private void AddObject(string name, int ID)

{

CustomDataType newObjectData = new CustomDataType();

newObjectData.name = name;

newObjectData.ID = ID;

AllObject.Add(newObjectData);

}

The problem comes when a second object is added to the world. When the function creates the data variable for this second object it overwrites all the information for the first object.

I realize this is happening because (in my example above) “newObjectData” is being added to the list by reference. However, even if I were to deep copy “newObjectData” and add the copy each time I called the function that copy would be overwritten.

How in the world do I handle this? Is there some way to make newObjectData a completely new variable each time the function is called?

I think this is a perfect example why posting pseudocode is a waste of time.
In this code newObjectData is a new object every time this function is run.
In this example code there is nothing to deep copy. You have a string and int.
Adding it to a list should not be overwriting any previous object reference.

That said, my C# isn’t practised enough to help you.

1 Like

Actually, I think it was helpful because you were right. The problem was somewhere else. There was nothing wrong with the code in this section.

1 Like