0评论

Unity中反射赋值共同变量

文章来自https://blog.csdn.net/u014761712/article/details/79154171 2019-03-18 58浏览

想免费获取内部独家PPT资料库?观看行业大牛直播?点击加入腾讯游戏学院游戏开发行业精英群711501594

首先创建一个基类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赋值过去,而不用一个一个赋值,但是不是同一个父类的物体不会被赋值。