Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Make object from JsonUtility.FromJson available

Discussion in 'Scripting' started by Jelmersb, Jul 13, 2016.

  1. Jelmersb

    Jelmersb

    Joined:
    Jul 12, 2016
    Posts:
    66
    Through JsonUtility.FromJson, I get an instance of an (serialized) class. But no matter what I try, I can't access the instance from anywhere else than Awake().

    Code (CSharp):
    1. void Awake(){
    2.         TextAsset targetFile = Resources.Load<TextAsset> ("Transactions") as TextAsset;
    3.         TransactionCollection data = JsonUtility.FromJson<TransactionCollection> (targetFile.text);
    4. }
    So "data" is only available in Awake(), even though I declared "public TransactionCollection data" in the beginning of the script...
     
  2. CrymX

    CrymX

    Joined:
    Feb 16, 2015
    Posts:
    179
    What is the value of data and targetFile if you do that ?
    Code (CSharp):
    1. public  TransactionCollection data;
    2.  
    3. public void Awake(){
    4.         TextAsset targetFile = Resources.Load<TextAsset> ("Transactions") as TextAsset;
    5.          if(targetFile == null)
    6.               Console.WriteLine("target file is null");
    7.         data = JsonUtility.FromJson<TransactionCollection> (targetFile.text);
    8. }
    9.  
    10. public void Update()
    11. {
    12. if(data == null)
    13.     Console.WriteLine("data is null");
    14. }
     
  3. SkaredCreations

    SkaredCreations

    Joined:
    Sep 29, 2010
    Posts:
    296
    You are re-declaring data variable in Awake, this is overriding the class property by creating a new variable in the current scope. Remove the word TransactionCollection from Awake (that is exactly what CrymX is doing in his post).
     
  4. Jelmersb

    Jelmersb

    Joined:
    Jul 12, 2016
    Posts:
    66
    Thank you both so much, it now works!
    I guess I should do some reading on C# to understand it all a bit better... :)
     
  5. jimroberts

    jimroberts

    Joined:
    Sep 4, 2014
    Posts:
    560
    Learn about variable scope and this issue will never haunt you again. Except when you start using closures...