Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Vitro · May 24, 2013 at 11:18 AM · serializationreflectionsecurityserializeserializefield

usage of FieldInfo.SetValue with SerializeField

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:

 public class TestVariables : MonoBehaviour {
     
     [SerializeField]
     private string string_test="nothing";
     
 }
 
 ==============================================
 
         [MenuItem("Tests/ Load String")]
         [ReflectionPermission(SecurityAction.Demand)]
     public static void Load ()
     {        
            string field_name = string_test;
            string field_content = "some data";
            FieldInfo finfo = type.GetField ( field_name , 
                   BindingFlags.Instance | BindingFlags.NonPublic|BindingFlags.Public );
            finfo.SetValue(currComponent,field_obj,BindingFlags.Instance | BindingFlags.NonPublic|BindingFlags.Public,null,null);
                         
     }



Suggestions, because this does not work?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Vitro · May 25, 2013 at 01:08 AM

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
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by Bunny83 · May 24, 2013 at 12:10 PM

This does work pretty well for me.

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.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Vitro · May 28, 2013 at 02:15 PM 0
Share

Did you save the non- monobehaviour objects? I just saw that they use only properties ins$$anonymous$$d fields.

Thank you

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

14 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to serialized a variable in a c# method? 1 Answer

How do you access the elements of a List at runtime using reflection? 3 Answers

Serializing NGUI UIFont - "Material doesn't have a color property '_Color'" 1 Answer

How to properly serialize fields and store them for use in play mode? 1 Answer

serialize static fields 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges