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
0
Question by Bypab212 · Nov 16, 2020 at 06:46 PM · unityeditorreflection

Is it possible to access a field from an editor without making it public?

It occurred to me to use reflection to access private fields and be able to modify them from the inspector or even from the editor script. But when I switch between scenes or open and close unity the values ​​disappear.

These are the scripts that I have used for testing. Player Script

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Player : MonoBehaviour {
 
     private string playerName = "Some Name";
     private int health = 100;
     private int xp = 75;
     private string[] items = new string[] { "Sword", "Shield" };
 
     public bool IsDead { get { return health <= 0; } }
     public int Level { get { return xp / 100; } }
 
     public void Heal(int heal) {
         health += heal;
     }
 
     public void Damage(int damage) {
         health -= damage;
     }
     
     public void AddXP(int xp) {
         this.xp += xp;
     }
 }

Field

 using System.Collections;
 using System.Collections.Generic;
 using System.Reflection;
 using UnityEngine;
 
 public class Field<T> {
 
     private Component component;
     private FieldInfo fieldInfo;
 
     public Field(string fieldName, Component component) {
         if (string.IsNullOrEmpty(fieldName))
             throw new System.ArgumentException("Field name cannot be Null or Empty.");
 
         this.component = component;
         fieldInfo = component.GetType().GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
     }
 
     public T GetValue() {
 
         return (T)fieldInfo.GetValue(component);
     }
 
     public void SetValue(T value) {
         fieldInfo.SetValue(component, value);
     }
 }

PlayerEditor

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEditor;
 
 [CustomEditor(typeof(Player))]
 public class PlayerEditor : Editor {
 
     private int heal = 0;
     private int damage = 0;
     private int xp = 0;
     private int length;
 
     public override void OnInspectorGUI() {
         Draw();
     }
 
     private void Draw() {
         Player player = (Player)target;
 
         // Fields.
         Field<string> nameField = new Field<string>("playerName", player);
         nameField.SetValue(EditorGUILayout.TextField("Name", nameField.GetValue()));
 
         EditorGUILayout.LabelField("Dead", player.IsDead.ToString());
 
         Field<int> healthField = new Field<int>("health", player);
         healthField.SetValue(EditorGUILayout.IntField("Health", healthField.GetValue()));
 
         EditorGUILayout.LabelField("Level", player.Level.ToString());
 
         Field<int> xpField = new Field<int>("xp", player);
         xpField.SetValue(EditorGUILayout.IntField("XP", xpField.GetValue()));
 
         EditorGUILayout.BeginHorizontal();
 
         // Display Items array.
         Field<string[]> itemsField = new Field<string[]>("items", player);
         length = EditorGUILayout.IntSlider("Items", length, 0, 4);
         
         if (GUILayout.Button("Update Items"))
             itemsField.SetValue(new string[length]);
 
         EditorGUILayout.EndHorizontal();
 
         for (int i = 0; i < itemsField.GetValue().Length; i++) {
             itemsField.GetValue()[i] = EditorGUILayout.TextField($"Item {i}", itemsField.GetValue()[i]);
         }
 
         // Buttons.
         EditorGUILayout.Space();
         EditorGUILayout.BeginHorizontal();
 
         heal = EditorGUILayout.IntField(heal);
         if (GUILayout.Button("Heal"))
             player.Heal(heal);
 
         damage = EditorGUILayout.IntField(damage);
         if (GUILayout.Button("Damage"))
             player.Damage(damage);
 
         EditorGUILayout.EndHorizontal();
 
         EditorGUILayout.BeginHorizontal();
 
         xp = EditorGUILayout.IntField(xp);
         if (GUILayout.Button("Add XP"))
             player.AddXP(xp);
 
         EditorGUILayout.EndHorizontal();
     }
 }


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

1 Reply

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

Answer by myzzie · Nov 16, 2020 at 07:03 PM

Unity already handles it for you!

 public class Example : MonoBehaviour
 {
     [SerializeField] private float myFloat;
 }

 [CustomEditor(typeof(Example))]
 public class ExampleEditor : Editor
 {
     public override void OnInspectorGUI()
     {
         serializedObject.Update();

         var myFloatProperty = serializedObject.FindProperty("myFloat");
         EditorGUILayout.PropertyField(myFloatProperty);

         serializedObject.ApplyModifiedProperties();
     }
 }


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

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

144 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 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 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 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 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 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 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 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 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 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 avatar image avatar image avatar image avatar image

Related Questions

Get a list of methodInfo/fieldInfo from a GameObject/Monobehavior like UnityEvent Field? 0 Answers

Unity custom editor when i modify byteArray field with reflection whitout SerializedProperty, it can not save. 1 Answer

CONTROL RIGIDBODY MOVEMENT 2 Answers

How to make elements added on runtime responsive in a vertical layout group in unity webgl? 0 Answers

Augmented Reality with markers 0 Answers


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