Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

IL2CPP and __makeref for ECS Components

Discussion in 'Entity Component System' started by CPlusSharp22, Nov 19, 2020.

  1. CPlusSharp22

    CPlusSharp22

    Joined:
    Dec 1, 2012
    Posts:
    111
    Hello, this is semi related to DOTS for me since I'm restricted to ECS component structs.
    I'm trying to make my component structs serializable but without having to write the code by hand with a basic interface. For example, if you have Serialize and Deserialize methods on the interface, every struct type that wants to implement that interface has to do so in each struct definition.

    I was looking into reflection, which while costly on its first use, could be used if the type information is cached. Such as FieldInfo[] that is provided by type.GetFields() . I can store that on initialization for each implementation of the interface, and then when I want to Read or Write values to the component - I'd do something like

    Code (csharp):
    1. void Deserialize(ref Reader reader)
    2. {
    3.     Vector3 deserializedVector = reader.ReadVector3();
    4.     var serializeableStruct = default(SerializeableStruct);
    5.     FieldInfo vectorField = static_CachedFields[0]; // type.GetFields()[0] equivalent but was stored somewhere prior on load
    6.     TypedReference refToStruct = ___makeref(serializeableStruct);
    7.     vectorField.SetValueDirect(refToStruct, deserializedVector);
    8. }
    This however does not appear to work with IL2CPP from what I'm reading, TypedReference is no good?
    https://forum.unity.com/threads/system-typedreference-bugged-cant-figure-out-how-to-use-it.570736/
    https://forum.unity.com/threads/how-can-i-create-a-typedreference.490440/

    Is there perhaps some Unity black magic somewhere in the DOTS package(s) that could help me achieve what I'm trying to do?