• 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
Question by oliver-jones · Feb 26, 2017 at 11:59 AM · jsonstaticconstant

Export Const Class with JSON

Hello,

I'm using a class to define a bunch of constants within my game. Like this:

 public class GameConstants{
 
    public const int BUILD_TIME = 20;
    public const int BUILD_COST = 100;
    public const int BUILD_TYPE = 2;
 }
 //etc...


I wish to be able to export this class to a JSON file so I can share among other 3rd parties. However, it's as if the Json doesn't even see, or read the 'const' variables. It returns an empty JSON.

However, if I include a normal variable within that class 'public int _hello = 0'. Then the JSON will pick that up, and include it into the JSON string, but not the CONSTS.

 static void ExportConstJson(){
 
         GameConstants _object = new GameConstants();
         string _json = JsonUtility.ToJson(_object);
         print("Json: " + _json);
     }

Is there any reason for this? Or a solution?

Thanks.

Comment

People who like this

0 Show 0
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
Best Answer

Answer by Bunny83 · Feb 26, 2017 at 12:54 PM

Const fields are not variables, they are constants. They are pretty much the exact opposite of variables. Constants are never serialized by any serialization system since they can never be deserialized as they are readonly and static. Static fields are never serialized either.

You basically have two options:

  • Store those "constants" in actual variables and serialize them in Unity. You usually would use a ScriptableObject for this.

  • Reverse the logic and store those setting in a JSON file and load that JSON file at runtime into variables. Actually a lot companies use this approach as they can hand over the json file to the gamedesigner (who often is not a programmer) and let him do the balancing. In the final build you usually integrate the JSON into the game so it can't be changed that easy from outside.

edit
Here's a small helper class that lets you easily export all public static fields (which includes const fields) of a given class type as JSON:

 using System.Text;
 using System.Reflection;
 using System;
 
 public static class StaticExporter
 {
     public static string Export<T>()
     {
         return Export(typeof(T));
     }
     public static string Export(Type aType)
     {
         StringBuilder sb = new StringBuilder();
         sb.AppendLine("{");
 
         var fields = aType.GetFields(BindingFlags.Static | BindingFlags.Public);
         for(int i = 0; i < fields.Length; i++)
         {
             var t = fields[i].FieldType;
             var v = fields[i].GetValue(null);
             SerializeFieldName(3, fields[i].Name, sb);
             if (IsNumber(t))
                 sb.Append(Convert.ToDouble(v));
             else if (t == typeof(bool))
                 sb.Append((bool)v ? "true" : "false");
             else if (t == typeof(string))
                 sb.Append('"').Append((string)v).Append("\"");
             else
                 sb.Append("null");
             if (i < fields.Length)
                 sb.Append(",");
             sb.AppendLine();
         }
         sb.AppendLine("}");
         return sb.ToString();
     }
     private static void SerializeFieldName(int aPrefix, string aName, StringBuilder aSb)
     {
         aSb.Append(' ', aPrefix);
         aSb.Append('"').Append(aName).Append("\" = ");
     }
 
     private static bool IsNumber(System.Type aType)
     {
         if (!aType.IsValueType)
             return false;
         return (
             aType == typeof(int) || aType == typeof(uint) ||
             aType == typeof(long) || aType == typeof(ulong) ||
             aType == typeof(short) || aType == typeof(ushort) ||
             aType == typeof(byte) || aType == typeof(sbyte) ||
             aType == typeof(float) || aType == typeof(double)
             );
     }
 }

So in your case you just have to do:

 Debug.Log(StaticExporter.Export<GameConstants>());

Note that this method only supports usual number types (see IsNumber), boolean and strings. All other static fields will be exported as "null". Though feel free to extend it if you need to.

Comment

People who like this

0 Show 2 · 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 oliver-jones · Feb 26, 2017 at 02:45 PM 0
Share

okay thanks for that. So either way, the logic still can't be saved as a Const. If I reverse the logic, and use JSON to hold the variables (and serialise them into Unity), they still can't be a const then? Thanks.

avatar image Bunny83 oliver-jones · Feb 26, 2017 at 08:15 PM 0
Share

No, not when you want to use one of the usual serialization methods out there. If you really want / need them as const fields you have to serialize them yourself. Either by writing custom code for each field, or by using reflection to iterate over all fields.

edit
I just added an example on "how to use reflection" to my answer.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

65 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

Related Questions

Vector3 as Constant in Script 1 Answer

How does one inspect static vars? 3 Answers

Problem with Static Variable? 1 Answer

Non-Static Accessibility 1 Answer

Help with Error: An instance of type 'Regex' is required to access non static member 'Replace'. 2 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