Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to work with managedReferenceValue?

Discussion in '2019.3 Beta' started by menderbug, Oct 20, 2019.

  1. menderbug

    menderbug

    Joined:
    May 14, 2018
    Posts:
    26
    I'm really excited about the new [SerializeReference] feature, and I'm trying to write a custom property drawer for a serialised polymorphic field (the base class is abstract in fact, but I don't think that makes a difference?). However, I'm not sure how to actually get the current value out. It seems that
    managedReferenceValue
    only has a setter. How do I actually get access to the currently serialised object?

    Another point of confusion: the new docs state that all of
    managedReferenceValue
    ,
    managedReferenceFullTypename
    and
    managedReferenceFieldTypename
    are write-only. However, it seems that actually only the value property is write-only, whereas the two type name properties are actually read-only? Is this a mistake in the docs?
     
  2. billykater

    billykater

    Joined:
    Mar 12, 2011
    Posts:
    327
    The basic problem with managedReferenceValue is how to expose multiple different values if the serializedobject represents multiple targets.

    What I did to check if the managedReferenceValue is null (so I can show a create entry of class A or B button) is to go through fieldInfo.

    using
    Code (CSharp):
    1. var value = fieldInfo.GetValue(property.serializedObject.targetObject)
    Allows you to get the value of one targetObject, if you need to support targetObjects you will need to extend this and handle multiple values accordingly.
    After the instance has been created you can just use FindPropertyRelative and the normal iteration stuff to access all fields of that serialized class.
     
    menderbug likes this.
  3. menderbug

    menderbug

    Joined:
    May 14, 2018
    Posts:
    26
    Awesome, thank you. I'm not really concerned about multi-object editing for now, so this should do. I'll give this a shot later today.
     
  4. menderbug

    menderbug

    Joined:
    May 14, 2018
    Posts:
    26
    Hmmm, one thing that's slightly awkward with this solution is that my actual SerializedProperty is not a field of targetObject, but has a deeper propertyPath (i.e. it's actually a field of one of the targetObject's fields). Is there a clean way to get the actual object that contains the relevant field?

    For now I'll probably just split the propertyPath on periods and walk down the tree manually. Seems kinda clunky though.