StackAsk is a community where developers ask questions, share answers and learn from each others real-world experience, so every solved problem helps the next person who runs into it.
using System; using UnityEngine; public class Player : MonoBehaviour { //Create a custom struct and apply [Serializable] attribute to it [Serializable] public struct PlayerStats { public int movementSpeed; public int hitPoints; public bool hasHealthPotion; } //Make the private field of our PlayerStats struct visible in the Inspector //by applying [SerializeField] attribute to it [SerializeField] private PlayerStats stats; }
Serializable
SerializeField
class UnityEditor { static void Main() { Assembly assembly = Assembly.GetExecutingAssembly(); Type[] serializableTypes = assembly.GetTypes() .Where(t => t.GetCustomAttributes(typeof(Serializable), true).Length > 0) .ToArray(); foreach (Type type in serializableTypes) { Console.WriteLine(type.FullName); } Type playerType = typeof(Player); FieldInfo[] serializedFields = playerType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .Where(f => f.GetCustomAttributes(typeof(SerializeField), true).Length > 0) .ToArray(); foreach (FieldInfo field in serializedFields) { Console.WriteLine($"Serialized field name: {field.Name}"); } } }
class UnityEditor { static void Main() { Object player = MonoBehaviourManager.Instance.GetBehaviour("player"); Type playerType = typeof(Player); FieldInfo[] serializedFields = playerType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .Where(f => f.GetCustomAttributes(typeof(SerializeField), true).Length > 0) .ToArray(); foreach (FieldInfo field in serializedFields) { field.SetValue(player, GetFieldValue(field.Name, field.GetType()); } } }
2.2K Point(s)
1.2K Point(s)
313 Point(s)
178 Point(s)
138 Point(s)
Input your email to receive reset password link, or if you remember your password, you can click