Search Unity

Reflection with colliders error (Auto Mass) 5.3.1 - "Density cannot be set on the collider unless...

Discussion in 'Scripting' started by Zandry, Feb 9, 2016.

  1. Zandry

    Zandry

    Joined:
    Oct 8, 2014
    Posts:
    2
    Hey Everyone,

    I've upgraded to 5.3.1 and had an issue with reflection - Colliders,Rigidbodies, and auto mass. I've created an extension function for components to set themselves to each other with reflection, you just pass for example something like:

    colliderA.SetFrom(colliderB);

    Then colliderA should have the same values as colliderB.
    This was always working fine but for some reason this exception is being thrown because of the auto-mass feature.

    All of my objects don't use auto-mass, so there are no set collider densities. It actually is hidden from the inspector and I never intend to use it. So is there a flag I should be adding so that my colliders being set with reflection don't attempt to set density? I would understand this error if I had two objects, one using auto-mass one not, but both are not. It's like the collider's density property is still considered "Canwrite".

    Here's my code. I'm not sure if that is enough but there is a catch{} which should remove the exception but I have no idea what kind of exception that is, maybe it's just

    Code (CSharp):
    1. public static T SetFrom<T>(this Component comp, T other) where T : Component {
    2.         System.Type type = comp.GetType();
    3.         if (type != other.GetType()){
    4.             return null; // type mis-match
    5.         }
    6.         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
    7.         while(type!=typeof(Component)){
    8.             PropertyInfo[] pinfos = type.GetProperties(flags);
    9.             foreach (var pinfo in pinfos) {
    10.                 //Debug.Log(comp.GetType() + ", " + pinfo);
    11.                 if (pinfo.CanWrite) {
    12.                     try {
    13.                         pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
    14.                     }
    15.  
    16.                     catch{}
    17.                 }
    18.             }
    19.             FieldInfo[] finfos = type.GetFields(flags);
    20.             foreach (var finfo in finfos) {
    21.                 finfo.SetValue(comp, finfo.GetValue(other));
    22.             }
    23.             type = type.BaseType;
    24.  
    25.         }
    26.         return comp as T;
    27.     }
    Thanks in advance, I've checked around on this issue but auto mass seems pretty new.
     
  2. Zandry

    Zandry

    Joined:
    Oct 8, 2014
    Posts:
    2
    I got it,

    Removing the binding flag "BindingFlags.Instance" made reflection ignore the colliders density property