我有这个代码来查找我的变量:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Reflection;
using System;
public class Shop : MonoBehaviour
{
public MoneyScript MS;
[SerializeField] GameObject ChosenObject;
string VarName = "speed";
public float Price;
public void OnMouseDown()
{
var Instance = ChosenObject.GetComponent<UpgradeValues>();
var Value = typeof(UpgradeValues).GetField(VarName, BindingFlags.Public | BindingFlags.Instance).GetValue(Instance);
Value = 100;
}
}
变量就在这个脚本中。它很小,因为我只想知道如何将其用于我的实际项目。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UpgradeValues : MonoBehaviour
{
public float speed = 3;
}
我尝试了这段代码,它没有提供任何错误!但是,该变量根本没有转换。
实际上,您实际上首先不会在您的用例中使用反射!
您已经拥有相应的实例参考
var 实例 = ChosenObject.GetComponent();
你的领域
public
对所有人来说都是可见的。所以你宁愿简单地经历
Instance.Value = 100f;
完成!