Unity 反射赋值共同变量
程序员文章站
2022-07-14 11:32:50
...
1 创建一个基类Demo ,然后在 子类,创建不同的变量类型 ,然后在同一个物体下可以赋值两个共有的变量,效果如下
,
- 第一先写基类的共有属性,及其反射获取属性值
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);
}
}
}
- 第一个继承类FirstCharacter
using UnityEngine;
using System.Collections;
public class FirstCharacter : CharacterEditor {
public GameObject[] other;
}
- 第二个继承类 SecondCharacter
using UnityEngine;
using System.Collections;
public class SecondCharacter : CharacterEditor {
//不同的属性
public int[] Origin;
}
放在同一个物体上点击同一个物体的”Copy With Reflection” 以及:”Paste With Reflection” 就可以直接从copy赋值过去,而不用一个一个赋值,但是不是同一个父类的物体不会被赋值。
上一篇: python之xpath基础使用
下一篇: 使用卷积网络做手写数字识别
推荐阅读