Skip to content

Instantly share code, notes, and snippets.

@karimkod
Last active January 5, 2020 14:46
Show Gist options
  • Save karimkod/51459670b8bb927805590b66cd2f91f3 to your computer and use it in GitHub Desktop.
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
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