拖拽指定序列化的私有变量(用代码实现)

1.先看这样一个脚本,我们要用代码来实现类似拖拽的方式指定引用,尤其是特别注意私有变量 mRootCanvas是怎样指定的。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIRoot : MonoBehaviour
{
    public Transform Bg;

    public Transform Common;

    public Transform PopUp;

    public Transform Forward;

    [SerializeField]
    private Canvas mRootCanvas;
}

 

2.代码片段(主要部分):

       var uiRootScript = uiRootObj.AddComponent<UIRoot>();

     //指定 public 的引用 (其中bg common popUp forward 都是些变量名,它们都是GameObject游戏物体)
uiRootScript.Bg
= bg.transform; uiRootScript.Common = common.transform; uiRootScript.PopUp = popUp.transform; uiRootScript.Forward = forward.transform; //指定序列化后的私有变量的引用:其中canvas是变量名,类型是GameObject。
先把整个脚本序列化,然后拿到里面的私有变量mRootCanvas,然后为其指定引用(objectReferenceValue),最后保存修改。
var uiRootSerializedObj = new SerializedObject(uiRootScript); //把目标脚本序列化 uiRootSerializedObj.FindProperty("mRootCanvas").objectReferenceValue = canvas.GetComponent<Canvas>(); //指定引用 uiRootSerializedObj.ApplyModifiedPropertiesWithoutUndo(); //保存修改

用到的 API 有:

SerializedObject()
FindProperty()
objectReferenceValue    //是个属性,用来指定引用
ApplyModifiedPropertiesWithoutUndo()

00

原文地址:https://www.cnblogs.com/rollingyouandme/p/12393003.html