- Home /
Array.Copy still creating a reference.
Hey all,
So I am trying to create a copy of an array so that I can revert back to the original array later. But for some reason I can't seem to make a copy and always get a reference.
Here is my code:
MeshRenderer[] tempArray = AffectedObject.GetComponentsInChildren<MeshRenderer> ();
m_PrevShaders=new MeshRenderer[tempArray.Length];
Array.Copy(tempArray,m_PrevShaders,tempArray.Length);
if (tempArray.Length>0)
for (int i=0; i<tempArray.Length; ++i) {
Shader tempShader=Shader.Find(m_ShaderName);
tempArray [i].material.shader = tempShader;
tempArray[i].material.SetColor("_OutlineColor",m_Color);
}
Any idea why it's not working? I think it might be because I'm copying a MeshRenderer or something but am not sure.
Thanks
You are getting a new array. However $$anonymous$$eshRenderes, are passed by reference. So you get a reference to the same $$anonymous$$eshRenderer.
Answer by NoseKills · Nov 05, 2014 at 06:37 PM
Like @BoredMoron said, if you have an array of 10 instances of MeshRenderer (or whatever class), if you Array.Copy the array, you still have the same 10 MeshRenderers, but now you have 2 arrays referencing them.
You might think "Why can't i just make temporary backups like this? Why did they make this so difficult".
If you look at what inherited members MeshRenderer has, it's easy to see why that wouldn't actually make things any easier.
Imagine you'd do duplicates of your MeshRenderers. OK, now in the new MeshRenderers, does meshRenderer.gameObject refer to the same GameObject as in the original one or should we then duplicate the associated GameObjects too? What about attached colliders ? Transforms ? etc...
Depending on how you'd answer the questions above, by making a backup of a small set of MeshRenderers, you'd be either A) making also a huge bunch of other objects easily wasting tons of memory, or B) ending up with the same problem as you have: the copies are not entirely new copies but instead referencing some of your old stuff.
Well copying all of the entire gameobjects would be even worse. If thats really what I have to do to get a copy of just this one piece I want that's kinda terrible. I just want the Shader. I have another way I can do it but this is just annoying.
The way to solve this would be to make simply store the variables you plan to change. Then set those back to the original when you are done
Your answer
Follow this Question
Related Questions
How to copy part of an array 2 Answers
Array.Copy in UnityScript 1 Answer
Problem with copying array that holds Raycasthit objects 1 Answer
How do I Resize an Array in JS? 1 Answer