我不知道如何使用反射SetValue

本文关键字:SetValue 反射 何使用 我不知道 | 更新日期: 2023-09-27 18:07:04

我一直试图使用反射一段时间了,可悲的是我的努力导致我的错误,我要做的是从另一个脚本得到一个整数的字段,并改变它,这是我的代码:

第一个脚本

using UnityEngine;
using System.Collections;
public class GameInformation : MonoBehaviour 
{
    void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }
    //1 is bought while 0 is not bought
    public static int TipJar;
}

我的第二个剧本

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

public class Upgrades : MonoBehaviour 
{
    public GameInformation gio;
    void Start()
    {
        gio = GameObject.Find("lol").GetComponent<GameInformation>();
        Type myClassType = gio.GetType().GetField("TipJar").SetValue(gio, 1, null); //<-- Error
    }
}

任何想法?抱歉问了一个无聊的问题,我还在学习如何编程,提前感谢!

我不知道如何使用反射SetValue

您需要GetField(string name, BindingFlags flags)的重载变体

gio.GetType().GetField("TipJar", BindingFlags.Static | BindingFlags.Public).SetValue(null, 1);

tks的答案应该适用于您,我只是想补充指出,您不需要GameInformation的实例。你可以这样写:

typeof(GameInformation).GetField("TipJar", BindingFlags.Static | BindingFlags.Public).SetValue(null, 1);

所以基本上你不需要找到GameInformation的实例引用来获得静态字段