Duplicate Array Element

Hello,

Unity has a built-in editor array property. With right click at an array element, you can choose “duplicate array element”.

Duplicating this way, all the serialized properties are copied.

In trying to do something similar but I do not how.

I have something similar to this:

[Serializable]
public class Foo()
{
    public GameObject prefab;
}

private void CopyFrom(List list, Foo copy)
{
    Foo newFoo = new Foo();
    newFoo.prefab = copy.prefab;     //NullReferenceException: Object reference not set to an instance of an object
    list.add(newFoo);
}

Any idea, anyway to get to the built-in copy element method?

Thank you.

By the way, I have seen this method:
public static void EditorUtility.CopySerialized(Object source, Object dest);

The problem is it forces the class to be a UnityEngine.Object, not just a Serializable

//Your list should be defined.
public class Foo {
    public GameObject prefab;

    public Foo Clone() {
        return new Foo
        {
            prefab = this.prefab
        };
    }
}

//then you clone it like so
    private void CopyFrom(List<Foo> list, Foo copy) {
        var foo = copy.Clone();
        list.Add(foo);
    }

Unless, of course, I am not following your thought pattern.

NullRef will happen there if the copy object you’re sending in is null.

You should only use EditorUtility stuff if it’s editor-only code. Those classes does not exist in a build.

Your naming is really bad here. You’re adding a copy of an object to a list. That’s not CopyFrom, that’s CopyTo. The object you’re sending in is also not copy, it’s either toBeCopied (bad), or better original:

private void CopyTo(List<Foo> list, Foo original) {
    if(original == null) {
        //handle that. It's probably not something you want, so to add information:
        throw new NullReferenceException("Trying to copy null to a list!");
    }
    
    Foo copy = new Foo();
    copy.prefab = original.prefab;
    list.Add(copy);
}

You could use JsonUtility to create a copy of the object, as that uses Unity’s serializer under the hood:

//instead of creating the copy
list.Add(JsonUtility.FromJson(JsonUtility.ToJson(original)));

But if the original inherits from UnityEngine.Object, that’ll just copy a reference, I beliveve.

1 Like

I agree with you with bad naming. The worse name is the title, because I want to make a copy IN EDITOR TIME, not in runtime.

That is not actually my code, it just a simplified example.
What I really want to know is how unity do it, because it is clear for me that it is some kind of reflection, not a custom method as Clone or something like this.

Anyway I have tried

            fooArray.list.Add(JsonUtility.FromJson<Foo>(JsonUtility.ToJson(foo)));

and seems to work perfecly. I will take a closer look but I think it is the right answer. Thank you!

Finally, list.Add(JsonUtility.FromJson<Foo>(JsonUtility.ToJson(foo))) works perfectly. Thank you very much!