Actually, there are two sheets in different scripts at some point in time one should become equivalent to another one. Well, I:

public void CopyMyList( List<GameObject> newList) { if(oldList !=null) { oldList = null; oldList = newList; } } 

How bad is this practice and how can it be curtailed? PS While everything works

    2 answers 2

    Assignment to null not necessary. All the same you next line overwrites this most null . Nothing wrong with that, just an extra operation.

    Note that you do not copy the list at all, despite the name of the function. Since List<T> is a reference type, you simply write in the oldList link to the same list that comes to you in newList . If you really need a copy of the list, the easiest thing to do is:

     public void CopyMyList( List<GameObject> newList) { if (oldList != null) // я сохраняю ту же логику oldList = newList.ToList(); } 

    As @ iluxa1810 correctly suggests in the comments, even with this, the list will still contain links to the same objects , from the changes in these objects in the newList list will be “visible” and in the oldList list. If this is not what you need, you will have to clone and objects. To do this, in the GameObject you need to implement the ICloneable interface, and instead of oldList = newList.ToList() write a more complex oldList = newList.Select(o => (GameObject)o.Clone).ToList() .

    • I think it is worth pointing out that this is not a complete copy. Ie if a sheet contains reference objects, then changing objects in one sheet, they will also change in the other. - iluxa1810
    • @ iluxa1810: Yes, but the question arises here: what of the links inside the object to consider as the “inner part” of the object itself, and what about the links to external entities. I will add the answer. - VladD
    • Thanks for the answer. I do not need a true copy in this case. It is just necessary that the script has access to the current list of objects. - astion
    • @astion: Understood, then simply oldList = newList . - VladD

    C # will clear for you the memory allocated for the old list, therefore oldList = null can be oldList = null .

    Another thing is that these two variables will point to the same list, and deleting an element from one will affect the other (very simply)

    • I tried not to write - but in the end, for some reason, nothing was copied anywhere - to see some internal features of Unity3d - astion