Search Unity

Question How would I copy AudioSource curves?

Discussion in 'Editor & General Support' started by lcscout, May 19, 2022.

  1. lcscout

    lcscout

    Joined:
    Apr 18, 2021
    Posts:
    2
    Hi, I made a custom editor for AudioSource where I can reference another AudioSource and any changes made are transfered to that reference.

    In order to actually making these changes I'm using the code for copying component I found here in the forum:

    Code (CSharp):
    1. public static T CopyComponent<T>(T original, GameObject destination) where T : Component {
    2.         Type type = original.GetType();
    3.         Component existing = destination.GetComponent(type);
    4.         if (existing != null)
    5.             DestroyImmediate(existing);
    6.         Component copy = destination.AddComponent(type);
    7.         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
    8.         PropertyInfo[] properties = type.GetProperties(flags);
    9.         FieldInfo[] fields = type.GetFields(flags);
    10.         foreach (PropertyInfo property in properties) {
    11.             if (property.Name == "minVolume" || property.Name == "maxVolume" || property.Name == "rolloffFactor" || property.Name == "name")
    12.                 continue;
    13.             try {
    14.                 property.SetValue(copy, property.GetValue(original, null), null);
    15.             }
    16.             catch { }
    17.         }
    18.         foreach (FieldInfo field in fields)
    19.             field.SetValue(copy, field.GetValue(original));
    20.         return copy as T;
    21.     }

    The problem appears to be that AudioSource curves are neither properties or fields so I dont know how I could copy them.

    Duplicating the object is not an option.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,736
    While I haven't tried it, I image that a good first place to start would be to call
    GetCustomCurve()/SetCustomCurve()
    with the
    AudioSourceCurveType
    enums that interest you.
     
    lcscout likes this.
  3. lcscout

    lcscout

    Joined:
    Apr 18, 2021
    Posts:
    2
    Thanks! That worked, although I had to make a custom copy method just for AudioSources