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 hatzalex · Nov 03, 2011 at 10:11 AM · arraynullreferenceexceptiontextfieldtxt

Writing to txt file using textfield problem

Hallo everybody,

I'm trying to store written Strings from a TextField into an external file (.txt file) and then read those strings from the .txt file and load them into an Array for in game usage. While the reading from file function works perfectly i can't seem to make the write function work. When i build the scene with the textField contained i get an NullReferenceException, but i just can't seem to find why. Here is my code:

manualKeyboard Script:

 private var currentWordLabel: wordControl;
 
 var stringToEdit : String;
 var myStyle : GUIStyle;
 var delay = 0;
 
 function Start ()
 {
     currentWordLabel = FindObjectOfType(wordControl);
 }
 
 function OnGUI () {    
     stringToEdit = GUI.TextField(Rect(100,100,200,20), stringToEdit, 25, myStyle);
             
     //if (currentWordLabel != null)
     //{
         currentWordLabel.AddToFile(stringToEdit);
     //}
 }


wordControl script:

 import System.IO;
 
 var sr : StreamReader;
 var sw : StreamWriter;
 
 var wordArray : String[];
 var currentWord :String;
 var maxAmount : int = 30;
 var currentAmount : int = 0;
 
 function Start () {}
 
 function changeWord () {    
     var randomInt = Random.Range(0,currentAmount);        
     currentWord = wordArray[randomInt];    
     guiText.material.color = Color.red;        
     guiText.text = currentWord;    
 }
 
 function LoadFile () {
     try {
         // Create an instance of StreamReader to read from a file.
         sr = new StreamReader("words_english.txt");                
         // Count amount of words in file
         currentAmount = 0;        
         while (sr.ReadLine() != null && currentAmount < maxAmount) {
             currentAmount++;
         }
         Debug.Log("Size is:" + currentAmount.ToString());
         wordArray = new String[currentAmount];
                 
         sr = new StreamReader("words_english.txt");
         // Fill array with words from file
         var i : int = 0;
         var line : String = sr.ReadLine();
         while (line != null && i < maxAmount) {    
             wordArray[i] = line;
             Debug.Log("Added word: " + line);
             line = sr.ReadLine();            
             i++;
         }
         
         sr.Close();
     }
     catch (e) {
         // Let the user know what went wrong.
         print("The file could not be read:");
         print(e.Message);
     }
 }
     
 
 
 function AddToFile (word : String) {
     try {
         // Create an instance of StreamWriter to write text to a file.
         sw = new StreamWriter("words_english.txt");        
         // Add some text to the file.   
         //sw.Write("The date is: ");
         sw.WriteLine(word);        
         sw.Close();
     }
     catch (e) {
         // Let the user know what went wrong.
         print("File coudn't be accessed:");
         print(e.Message);
     }  
     
     LoadFile();
 }

Am i doing something wrong or isn't it possible to write to txt files using textfields?

Thanks in advance

Comment
Add comment · Show 6
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 syclamoth · Nov 03, 2011 at 10:13 AM 0
Share

TextFields are just a way of manipulating string data- there is absolutely no way that it's impossible to write to a txt file just because you are using them.

avatar image DaveA · Nov 03, 2011 at 05:31 PM 0
Share

Hit 'edit', select all your code, hit the 101/010 button to format your code please

avatar image cj_coimbra · Nov 03, 2011 at 08:32 PM 0
Share

I don´t know if it´s related but you could use text assets ins$$anonymous$$d of streams. If you happen to work with iOS or OSX, streams won´t work.

avatar image jahroy · Nov 03, 2011 at 09:31 PM 0
Share

Why wouldn't streams work on OS X? I believe that is not true.

avatar image hatzalex · Nov 03, 2011 at 09:46 PM 0
Share

Sorry for the inconvinience guys, i did format it but something went wrong as it seems. Should be fixed now.

Show more comments

2 Replies

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

Answer by jahroy · Nov 03, 2011 at 08:29 PM

It looks like currentWordLabel could be null.

You need to make sure it's not null and that it's initialized.

Ironically it looks like you commented out the code that checks for null...

currentWordLabel = FindObjectOfType(wordControl);

if ( currentWordLabel == null ) { print("Something is wrong."); }

Comment
Add comment · Show 6 · 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 hatzalex · Nov 03, 2011 at 10:42 PM 0
Share

It is this line. The one that calls upon the wordControl class:

     currentWordLabel.AddToFile(stringToEdit);
avatar image hatzalex · Nov 04, 2011 at 04:30 PM 0
Share

After some debugging i uncovered that the stringToEdit empty is.

 if(stringToEdit == null) Debug.Log(stringToEdit);

Of course in the debug log nothing shows up.

Which is very strange since i definitely give the string a value. $$anonymous$$aybe the textfield removes that value or something?

avatar image jahroy · Nov 04, 2011 at 06:46 PM 0
Share

You never check whether currentWordLabel is null... it probably is.

I just edited my answer...

avatar image hatzalex · Nov 07, 2011 at 08:18 AM 0
Share

CurrentwordLabel is indeed null.. but i don't understand why. I properly declare it and the string is also declared

avatar image jahroy · Nov 07, 2011 at 03:26 PM 0
Share

You declare it, but you never initialize it.

Then you set it to the return value of FindObjectOfType, but never check whether or not it succeeds.

I've never used FindObjectOfType (I think it's generally a bad idea) but I believe it looks for GameObjects in the scene. $$anonymous$$y guess is you want to use a different approach to obtain and initialize your wordControl object.

It's hard to help further without knowing what kind of object a wordControl is. If it's a simple class you probably need to initialize it using a constructor. Here is some example code that shows how to add constructors to a simple class. This example creates two constructors: one without parameters and one with two parameters. $$anonymous$$y example class is declared and defined at the bottom of the script.

 private var currentWordLabel : ExampleWordControl;
 
 
 /* create an instance of type ExampleWordControl */
 
 function Start ()
 {
     /* call the constructor that takes two parameters */

     currentWordLabel = new ExampleWordControl("test", 44);
 }
 
 
 /* example class (class names are capitalized) */
 
 class ExampleWordControl
 {
     var name  :  String;
     var num   :  int;
 
     /* example constructor */
 
     function ExampeWordControl ()
     {
         name = "Untitled";
         num  =  0;
     }
 
     /* example constructor with parameters */
 
     function ExampleWordControl ( someName, someNumber )
     {
         name = someName;
         num  = someNumber;
     }
 }


An easier way to do this (as long the wordLabel class is not complex) is to make it public and initialize it using the Inspector.

If wordLabel is a monoscript (a script that gets applied to GameObjects) it's a little different. You could use GetComponent to access another object OR you could make currentWordLabel public and drag and drop a GameObject with a wordControl script attached to it onto your script in the inspector.

Hope some of this makes sense...

Show more comments
avatar image
0

Answer by SteveOxen268 · Sep 21, 2013 at 09:34 PM

Work with word files by the use of fix documents word

Learn given item http://www.fixdoconline.fixdocfiles.com/

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

7 People are following this question.

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

Related Questions

Destroying Elements From An Array 1 Answer

NullException Error With Array of GameObjects 2 Answers

NullReferenceException with Javascript Array 2 Answers

Object reference not set when referencing it and adding to array 2 Answers

Problem with Singleton and NullReferenceException? 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