- Home /
Copy values from one object (scriptwise) to another
Hey guys, this might be a simple question but I couldnt find any related posts or questions. What I want to do is to make a script object the copy of another one. I'm trying to do this this way:
public var test : List.<Objects>;
public var localTest : List.<Objects>;
function OnEnable(){
localTest = test;
}
Apparently this only sends a reference to the first object, thus everything I do with the second one is actually happening to the first one. I am afraid that if i loop through the first one and add the values to the second one, it will also only save references to the first one.
Any help is much appreciated
Yeh thanks, i did see that but i am not writing it in c#. I Could conevrt it but i was hoping there is an out of the box option for unity script also
So you want to copy the elements of the list into a new list? Huh. Don't suppose you could...
foreach (Object obj in oldList) newList.Add(Instantiate(obj));
Thank you all for your answers, I think i will go for instantiating the object the contains it (and destroying). Since i will do this only every 15 seconds or so i hope it wont affect that much the performance of the game. And i will use pooling for the smaller assets.
I can guarantee you that you do not need to use pooling. Seriously. You're in a learning stage, and you should not spend time on learning to optimize before you learn to actually write working code.
It keeps infuriating me that tutorials thinks that object pooling belongs on the same level as say copying a list. They don't. There's months of learning between those two points.
If you don't have a grasp on the difference between objects and references to objects work - as your question shows - do yourself a favor and skip the object pooling for now.
Answer by tanuj0092 · Oct 30, 2014 at 01:09 PM
Once a List is created, it references the values from different memory locations. Eg. if you create an integer list then list[0], list[1]..etc actually points the value at that memory location, not the actual value. The instruction localtest = test actually passes the data of those memory locations to another list. So, what will happen, is when you edit the localtest list, it will automatically reflect in test list as well.
So, you need to create a new list and copy all elements in a loop as
for( int i = 0; i < test.count; i++ )
{
localtest.Add(test[i]);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613170319im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
problem with my simple script please help. 2 Answers
NullReferenceException: Object reference not set to an instance of an object Raycast...? 1 Answer
Why Does My GameObject Not Spawn Anymore? 2 Answers
How may I get the children (direct and dependents) of a game object? 2 Answers