Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Menyus777 · Apr 02, 2018 at 03:32 PM · c#listcomponentgenerics

How to Copy a Component if it contains List?

I would like to copy a component using reflection, but my List fields never get copied they just reference to the first instance of the script.

 T CopyComponent<T>(T original, GameObject destination) where T : Component
 {
     Type type = original.GetType();
     var my_Component = destination.GetComponent<T>();
     if (!my_Component)
     {
         my_Component = destination.AddComponent(type) as T;
     }
     FieldInfo[] fields = type.GetFields();
     foreach (FieldInfo field in fields)
     {
         if (field.IsStatic)
         {
             continue;
         }
         field.SetValue(my_Component, field.GetValue(original));
     }
     PropertyInfo[] props = type.GetProperties();
     foreach (PropertyInfo prop in props)
     {
         if (!prop.CanWrite)
         {
             continue;
 
         }
         prop.SetValue(my_Component, prop.GetValue(original, null), null);
     }
     return my_Component as T;
 }

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Menyus777 · Apr 02, 2018 at 04:39 PM

 using System.Collections;
 using System;
 using System.Reflection;
 using System.Collections.Generic;
 using UnityEngine;
 
 /// <summary>
 /// Allows you to copy a component and all of its values
 /// </summary>
 public class ComponentCopier{
 
     /// <summary>
     /// Copies a Component to the given GameObject, also ignores Static and Const variables
     /// </summary>
     /// <typeparam name="T">The type of your Component</typeparam>
     /// <param name="original">The instance of your Script</param>
     /// <param name="destination">The GameObject you want your component to be copied to</param>
     /// <returns>Returns a reference to your copied component</returns>
     public static T CopyComponent<T>(T original, GameObject destination) where T : Component
     {
         //We ask for the Component type
         Type type = original.GetType();
         //Checks if the gameobject already has that comp, if error pops try this with non generic version -> "destination.GetComponent(type) as T;"
         var my_Component = destination.GetComponent<T>();
         //If my component is null we add a T component
         if (!my_Component)
         {
             //Should not use Generic version here
             my_Component = destination.AddComponent(type) as T;
         }
 
         //returns all the public fields of the T
         FieldInfo[] fields = type.GetFields();
         foreach (FieldInfo field in fields)
         {
             //If Static we do not copy, cos it would hurt the basic principle of static and pretty sure would be a runtime error too, 
             //in c# Const is also static so your Const values will be ignored too which is perfect for us
             if (field.IsStatic)
             {
                 continue;
             }
             //We ask for the type of the field this can be Int32, !!!Float which name is System.Single in C# not System.Float!!!, also this logic is extremely handful for you if you
             //need to  extend this script further
             Type f_type = field.FieldType;
             //is the type Generic? -> <T>
             if (f_type.IsGenericType)
             {
                 //So because .Net 3.5 aint supporting some nice features for Generic type the below code can be read,
                 //Please note the below lines can make coders vomit easily so proceed with caution
                 //Gets the Generic Type>
                 Type elementType = f_type.GetGenericArguments()[0];
                 //Is the code is a list
                 if (f_type.ToString() == String.Format("System.Collections.Generic.List`1[{0}]", elementType))
                 {
                     //Lets ask the type of a List<>
                     Type type_of_a_list = typeof(List<>);
                     //Lets ask the type of a List<> that contains our specific type like this cutie here: List<Vector3>
                     Type copy_List = type_of_a_list.MakeGenericType(elementType);
                     //so what Activator.CreateInstance does is that it makes an instance, that we can copy our List<T>, what we will get from the original component
                     IList instance = (IList)Activator.CreateInstance(copy_List);
                     //Our original List, dont ever try to cast it into object, otherwise runtime error cant cast source to target
                     IList instance_original = (IList)field.GetValue(original);
                     //Basic component copy
                     foreach(var element in instance_original)
                     {
                         instance.Add(element);
                     }
                     field.SetValue(my_Component, instance);
                 }
                 else
                 {
                     //Implement if you want it, i dont atm....
                     MonoBehaviour.print("Your code contains a generic Type but your component copier does not Copied it!");
                 }
             }
             else
             {
                 field.SetValue(my_Component, field.GetValue(original));
             }
         }
         //Below code detects properties, if you are not sure what is a property check it in MSD: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
         PropertyInfo[] props = type.GetProperties();
         foreach (PropertyInfo prop in props)
         {
                 //if my property only has a get function then i cant read it
                 if (!prop.CanWrite)
                 {
                     continue;
                 }
             prop.SetValue(my_Component, prop.GetValue(original, null), null);
 
         }
         return my_Component as T;
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

469 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to create a List containing all the different variables within a script (regardless of type)? 1 Answer

How to read X and Y component ( of a vector2) from a list 1 Answer

PrefabHell - How to have scripts of prefabs instances reference the variables of the prefab instance they're attached to? 1 Answer

A node in a childnode? 1 Answer

How to create a generic list from a group of gameObjects with specific tag? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges