I am trying to do my own scene saving system, but I found a problem when I was doing the loading. I had tried to use the reflection method to do this, but I found a permission problem that I could not resolve. Here is the code:
Your code is a bit strange and misses a lot declarations / definitions. For example: are you sure that currComponent is a reference to the right component? Where do you set the “type” variable and does it have the Type reference for the desired component? Have you used currComponent.GetType() to get the Type? Are you sure that field_name actually contains the field name e.g. “string_test”? What is field_obj? Should it be field_content?
I guess the Lost function is part of an EditorScript? An Inspector or an EditorWindow?
And finally, what means “does not work”? Is it crashing? Do you get errors? Is the variable not set?
ps: You don’t need to give bindingflags to the SetValue function. This should be enough:
finfo.SetValue(obj, newValue);
Please when you post sample code, make sure it actually reflects a real example of your code.
Bunny83 is correct. this really works after you give your answer a had dug more in other parts of my system and found the real bug. Above The real test code, just to share. I learn that ReflectionPermission does not matter in unity to access fields.
using UnityEngine;
using System.Collections;
public class TestVariable : MonoBehaviour {
public string publicText="public text1 - initial";
[SerializeField]
private string privateText ="private SerializeField - initial";
}
=======================================
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;
public static class EditorReflectionTest {
[MenuItem("Debug/ChangeValue")]
public static void TestReflection()
{
if ((Selection.gameObjects == null) || (Selection.gameObjects.Length == 0))
{
Debug.LogError("Please select the object you wish to test.");
return;
}
Component comp = Selection.activeGameObject.GetComponent<TestVariable>();
if( comp == null )
{
Debug.LogError("Please select the object selected should have the component TestVariable.");
return;
}
FieldInfo public_finfo = comp.GetType().GetField ( "publicText" , BindingFlags.Instance | BindingFlags.NonPublic|BindingFlags.Public );
FieldInfo private_finfo = comp.GetType().GetField ( "privateText" , BindingFlags.Instance | BindingFlags.NonPublic|BindingFlags.Public );
public_finfo.SetValue(comp,"new value on public field");//works
private_finfo.SetValue(comp,"new value on private field");// works
GameObject go = new GameObject("new GO");
comp = go.AddComponent<TestVariable>();
public_finfo.SetValue(comp,"other thing on public field");//works
private_finfo.SetValue(comp,"other thing on private field");// works
}
}