Last active
January 5, 2020 14:46
-
-
Save karimkod/51459670b8bb927805590b66cd2f91f3 to your computer and use it in GitHub Desktop.
An extension method for WWWForm to add fields from public fields of an instance of a class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Reflection; | |
using System; | |
using UnityEngine; | |
public static class WWWFormExt{ | |
public static void AddFieldsFromObject<T>(this WWWForm form, T sourceObject) | |
{ | |
var serializableAttr = Attribute.GetCustomAttribute(sourceObject.GetType(), typeof(SerializableAttribute)); | |
var type = typeof(T); | |
FieldInfo[] objectFieldInfo; | |
objectFieldInfo = type.GetFields(BindingFlags.Instance | BindingFlags.Public); | |
for(int i = 0; i < objectFieldInfo.Length; i++) | |
{ | |
if(objectFieldInfo[i].FieldType == typeof(int)) | |
form.AddField(objectFieldInfo[i].Name, (int)objectFieldInfo[i].GetValue(sourceObject)); | |
else if(objectFieldInfo[i].FieldType == typeof(string)) | |
form.AddField(objectFieldInfo[i].Name, objectFieldInfo[i].GetValue(sourceObject).ToString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment