Hey guys, I’m back to working on my serialization engine and I’m having trouble with creating a typed reference.
Let me start with a NOTE: Normally my engine will build pre defined serialization instructions in the editor when the AssetDatabase refreshes for types that are marked with my custom serializable attribute. This means that the engine can serialize values even if they are not marked as System.Serializable. I’m not going to go into the background of why this function and attribute exist because it would take too long to explain. This is just a single feature of the engine.
However, in order to get the feature to work it needs to be able to set field values in structures. I was going to do this using GetField().SetValueDirect() but I am not sure how to express the struct as a TypedReference as required by the SetValueDirect method’s obj parameter.
Other Additional Info :
The struct I’m testing on is a Vector4 but comes back to the engine as object upon deserialize.
The engine extends the option to allow for building of serialization instructions at run time (so they only have to build once per play session) which is how Vector4 is being tested without my attribute. (This feature is only available if the user (programmer) selects it in the engine settings).
Conclusion :
How can I make a TypedReference for a struct? Thanks!
Yes, MakeTypedReference is throwing it because if I disable that line of code above the exception goes away.
maybe there’s another way to A. get a typed reference or B. to set field value in a struct? (This is a non issue in a class so I know the instruction progression is correct) And remember the struct is coming back upon deserialize as System.Object.
Judging by the fact that if I input a new FieldInfo[0] as the second parameter then the exception will instead say “the parameter “flds” is empty” (or something to that effect), I am assuming that the method is supported. Just a thought.
Hi, in case you (or anyone else) were still wondering how to do this – I’ve had to do this once before, and succeeded through use of the __makeref keyword. See below for example on how to employ the keyword for this purpose:
// Given:
Vector4 yourStruct;
FieldInfo yourStructField; // Just pretend this refers to the vector's x-component field.
float valueToAssign; // Let's say we want to assign this to the field mentioned above.
// How to do it:
TypedReference yourStructRef;
yourStructRef = __makeref(yourStruct); // Looks funky, but "__makeref" is actually a built-in C# keyword.
yourStructField.SetValueDirect(yourStructRef, valueToAssign); // You can now assign values in such a way.