Search Unity

Problem with creating text file with text assets

Discussion in 'Editor & General Support' started by 987054win, Apr 24, 2014.

  1. 987054win

    987054win

    Joined:
    Apr 12, 2014
    Posts:
    27
    Here's my code for creating text files


    Code (csharp):
    1. public class CreateText : MonoBehaviour {
    2.  
    3.  
    4.     void Start () {
    5.  
    6.         TextAsset Tester = new TextAsset ();
    7.         AssetDatabase.Refresh ();
    8.         AssetDatabase.CreateAsset (Tester,"Assets/Test.txt");
    9.         Debug.Log(AssetDatabase.GetAssetPath(Tester));
    10.         System.IO.File.WriteAllText ("Assets/Test.txt", "My Karma");
    11.         AssetDatabase.SaveAssets ();
    12.  
    13.     }
    14.    
    15.  
    16.  
    17. }
    I've got a NullReferenceException everytime I run the game. What did I do wrong, plss help.
     
  2. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    I don't know what the actual problem in your code is, but I don't think you're meant to create Assets at runtime the way you're doing.

    If you need to store a file at runtime, then you should probably use the System.IO classes to write the file to Application.persistentDataPath folder. That's guaranteed to be be writable and persistent between game sessions and even game updates.

    So replace your code with this:

    Code (csharp):
    1. void Start()
    2. {
    3.     var filePath = System.IO.Path.Combine(Application.persistentDataPath, "Test.txt");
    4.     System.IO.File.WriteAllText(filePath, "My Karma");
    5. }
    Haven't tested it but you get the idea.

    EDIT:
    Also you should post questions like this in the Scripting subforum.
     
    Last edited: Apr 24, 2014
  3. 987054win

    987054win

    Joined:
    Apr 12, 2014
    Posts:
    27