Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by hollym16 · May 10, 2016 at 04:02 PM · textdestroyscript errordelegatelanguage

Dont destroy object when changing scene

I'm using some scripts I found to change the language in my App. I've got a scene where I initially set the language then it changes it throughout the rest of the App.

However, when I return to the language selection menu, it defaults back to the start language (English) and I'm unable to change the language.

The Console shows the following error: MissingReferenceException: The object of type 'Text' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

I can't work out specifically which part of the script is doing this; I have 2 main scripts:

 using System.Runtime.InteropServices;
 using UnityEngine;
 using System.Collections.Generic;
 using UnityEngine.EventSystems;
 
 public static class TextLocalization
 {
     public static event Localize LocalizationChanged;
 
     private static readonly Dictionary<string, string[]> dictionary = new Dictionary<string, string[]>();
 
     private static TextLocalizationFiles localizationAsset;
     private static int nbLocaFiles;
 
     private static int currentLanguageIndex = -1;
     
     public static string[] AvailableLanguages { get; private set; }
     public static string CurrentLanguage { get { return AvailableLanguages[currentLanguageIndex]; } }
     public static List<string> Keys { get { return new List<string>(dictionary.Keys); }}  
 
     public static void Init()
     {
         localizationAsset = Resources.Load<TextLocalizationFiles>("Localization");
         if (nbLocaFiles != localizationAsset.files.Length || dictionary.Count == 0)
         {
             dictionary.Clear();
             foreach (TextAsset asset in localizationAsset.files)
                 Load(asset);
             nbLocaFiles = localizationAsset.files.Length;
         }
     }
 
     public static bool Load(TextAsset txt)
     {
         if (txt != null && LoadCSV(txt)) 
             return true;
         return false;
     }
 
     private static bool LoadCSV(TextAsset asset)
     {
         CSVReader reader = new CSVReader(asset);
 
         // The first line should contain "KEY", followed by languages.
         List<string> temp = reader.ReadCSV();
 
         // There must be at least two columns in a valid CSV file
         if (temp.Count < 2) return false;
 
         // Ensure that the first value is what we expect
         if (!string.Equals(temp[0], "KEY"))
         {
             Debug.LogWarning("Invalid localization CSV file. The first value is expected to be 'KEY', followed by language columns.\n" +
                 "Instead found '" + temp[0] + "'", asset);
             return false;
         }
 
         if (AvailableLanguages == null)
         {
             AvailableLanguages = new string[temp.Count - 1];
             for (int i = 1; i < temp.Count; ++i)
                 AvailableLanguages[i - 1] = temp[i];
         }
         else
         {
             if (AvailableLanguages.Length != temp.Count - 1)
             {
                 Debug.LogError(
                     string.Format("Localization file {0} does not have the correct amount of languages, expected {1} but got {2}",
                         asset.name, AvailableLanguages.Length, temp.Count - 1));
                 return false;
             }
         }
 
         // Read the entire CSV file into memory
         temp = reader.ReadCSV(); 
         while (temp != null)
         {
             string[] values = new string[temp.Count - 1];
             for (int i = 0; i < values.Length; ++i) values[i] = temp[i + 1];
             try
             {
                 dictionary.Add(temp[0], values);
             }
             catch (System.Exception)
             {
                 Debug.LogError(string.Format("Unable to add '{0}' to the Localization dictionary. Found the double in {1}", temp[0], asset.name));
             }
 
             temp = reader.ReadCSV();
         }
         return true;
     }
 
     /// <summary>
     /// Select the specified language from the previously loaded CSV file.
     /// </summary>
 
     public static bool SelectLanguage(string alanguage)
     {
         currentLanguageIndex = -1;
         for(int i = 0; i < AvailableLanguages.Length; ++i)
             if (AvailableLanguages[i] == alanguage)
             {
                 currentLanguageIndex = i;
                 break;
             }
 
         if (Application.isPlaying)
         {
             if(LocalizationChanged != null)
                 LocalizationChanged();
         }
 
         return currentLanguageIndex >= 0;
     }
 
     public static string Get(string key)
     {
         string[] vals;
 
         if (currentLanguageIndex != -1 && dictionary.TryGetValue(key, out vals))
         {
             if (currentLanguageIndex < vals.Length)
                 return vals[currentLanguageIndex];
         }
 
 #if UNITY_EDITOR
         Debug.LogWarning("Localization key not found: '" + key + "'");
 #endif
         return key;
     }
 
     public static string[] GetAll(string key)
     {
         string[] vals;
 
         if (dictionary.TryGetValue(key, out vals))
             return vals;
 
 #if UNITY_EDITOR
         Debug.LogWarning("Localization key not found: '" + key + "'");
 #endif
         return null;
     }
 
 
     public static bool Exists(string key)
     {
         return dictionary.ContainsKey(key);
     }
 }
 public delegate void Localize();

And this script:

 using UnityEngine;
 using UnityEngine.UI;
 
 [RequireComponent(typeof(Text))]
 public class TextLocalize : MonoBehaviour
 {
     public string key;
     private Text label;
 
     public string value
     {
         set
         {
             if (!string.IsNullOrEmpty(value))
             {
                 label.text = value;
 #if UNITY_EDITOR
             UnityEditor.EditorUtility.SetDirty(label);
 #endif
             }
         }
     }
 
     private void Awake()
     {
         TextLocalization.LocalizationChanged += OnLocalize;
         label = GetComponent<Text>();
     }
 
     private void Destroy()
     {
         TextLocalization.LocalizationChanged -= OnLocalize;
     }
 
     private void OnEnable()
     {
 #if UNITY_EDITOR
     if (!Application.isPlaying) return;
 #endif
         OnLocalize();
     }
 
     private void Start()
     {
 #if UNITY_EDITOR
     if (!Application.isPlaying) return;
 #endif
         OnLocalize();
     }
 
     public void OnLocalize()
     {
         if (string.IsNullOrEmpty(key))
             key = label.text;
 
         if (!string.IsNullOrEmpty(key)) value = TextLocalization.Get(key);
     }
 }
 

I thought it would just be a case of deleting the private void Destroy(){ function but this does nothing.

Which led me to believe it is something to do with the public delegate void Localize(); function.

Can anyone point me in the right direction please?

Comment
Add comment · Show 2
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 ARKMs · May 10, 2016 at 05:07 PM 0
Share

In What line throw the error?

And your OnEnable and Start do the same, you can remove Start.

avatar image hollym16 ARKMs · May 11, 2016 at 09:57 AM 0
Share

Thanks for replying. I have several error references: $$anonymous$$issingReferenceException: The object of type 'Text' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. TextLocalize.set_value (System.String value) (at Assets/LocaDemo/Assets/Localize/TextLocalize.cs:18) TextLocalize.OnLocalize () (at Assets/LocaDemo/Assets/Localize/TextLocalize.cs:48) TextLocalization.SelectLanguage (System.String alanguage) (at Assets/LocaDemo/Assets/Localize/TextLocalization.cs:112) GameController.Awake () (at Assets/LocaDemo/Assets/GameController.cs:7)

GameController script: using UnityEngine; public class GameController : $$anonymous$$onoBehaviour { private void Awake () { TextLocalization.Init(); TextLocalization.SelectLanguage("English"); } public void SelectLanguage(string aName) { TextLocalization.SelectLanguage(aName); } }

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Tyche10 · May 11, 2016 at 10:23 AM

I don't see you calling the Destroy function anywhere so it won't get called, and so you don't unsubscribe your listener to the event, which can throw a null reference. I think you probably meant to use the OnDestroy() function: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDestroy.html

Comment
Add comment · Show 3 · 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 hollym16 · May 11, 2016 at 01:42 PM 0
Share

Thanks for the reply.

I don't want to destroy the Text object but when I return to the language selection screen (containing the GameController script) it comes up with the error: $$anonymous$$issingReferenceException: The object of type 'Text' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

One of the scripts must be destroying the Text objects and preventing me from changing the language again.

Any ideas? (See the comment on the question to see the full error message)

avatar image Tyche10 hollym16 · May 11, 2016 at 02:02 PM 0
Share

I gather this problem occurs when you are changing scenes? Have you tried using the DontDestroyOnLoad function? http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

Even if you don't want to destroy, you should always coorectly unsubscribe an event listener from the event publisher before the listener is destroyed

      private void OnDisable()
      {
          TextLocalization.LocalizationChanged -= OnLocalize;
      }


avatar image hollym16 Tyche10 · May 11, 2016 at 02:16 PM 0
Share

Thank you!

Putting in the OnDisable script now means I can go back to be Select Language screen to select a different language without it causing errors.

The only thing that isn't quite right is that it reverts back to English because of the GameControllers Awake function:

private void Awake () { TextLocalization.Init(); TextLocalization.SelectLanguage("English"); }

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

48 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

Related Questions

How can I delete a line of UI Text? 0 Answers

Text in UnityEngine.UI doesn't work 0 Answers

GameObject destroyed when changing scene 1 Answer

Array cannot read Greek characters 1 Answer

Text in TextMeshPro looks weird 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