Unity reflection assignment common variable details, unity assignment variable details
1. Create a base class Demo, create different variable types in the subclass, and assign two common variables to the same object. The effect is as follows:
,
First, write the common attributes of the base class and obtain the attribute values through reflection.
using System;using UnityEngine;using System.Reflection;public class CharacterEditor : MonoBehaviour { public int health; public string name; public GameObject shirt; public GameObject pants; private static CharacterEditor characterCopyFrom; private static FieldInfo[] fileToCopy; [ContextMenu("Copy With Reflection")] public void CopyWithReflection() { characterCopyFrom = this; Type characterType = typeof(CharacterEditor); FieldInfo[] charcterFileds = characterType.GetFields(BindingFlags.Public | BindingFlags.Instance); fileToCopy = charcterFileds; } [ContextMenu("Paste With Reflection")] public void PasteWithReflection() { foreach (FieldInfo field in fileToCopy) { object value = field.GetValue(characterCopyFrom); field.SetValue(this,value); } }}
The first inheritance class FirstCharacter
using UnityEngine;using System.Collections;public class FirstCharacter : CharacterEditor { public GameObject[] other;}
Second inheritance class SecondCharacter
Using UnityEngine; using System. Collections; public class SecondCharacter: CharacterEditor {// different attributes of public int [] Origin ;}
Click "Copy With Reflection" and "Paste With Reflection" of the same object on the same object to assign values directly from copy instead of assigning values one by one, objects that are not the same parent class are not assigned a value.