Z
Z
Zimaell2021-02-25 13:55:20
Unity
Zimaell, 2021-02-25 13:55:20

Why does NullReferenceException appear the first time?

The bottom line is that I create text documents and then write data to them, the first method checks if there is such a thing and if not, it creates it, the second method takes data from these text documents and places it in variables

public float MusicVolume = 0.4f, SoundVolume = 0.2f;
private void Test1(){
        if(!Resources.Load("Data/MusicVolume")){
            StreamWriter writer = new StreamWriter("Assets/Resources/Data/MusicVolume.txt", false);
            writer.Write(MusicVolume);
            writer.Close();
............................................
            }

private void Test2(){
        TextAsset TX;
        string Value = "";
        TX = Resources.Load("Data/MusicVolume") as TextAsset;
        Value = TX.text.Replace(" ", "").Replace(',', '.'); // <---- ошибка сюда указывает, и все больше ошибок нету
        MusicVolume = float.Parse(Value, CultureInfo.InvariantCulture);
        TX = Resources.Load("Data/SoundVolume") as TextAsset;
        Value = TX.text.Replace(" ", "").Replace(',', '.');
.....................................

The problem is, the first time I run it, it gives me an error in the second method
NullReferenceException: Object reference not set to an instance of an object

But at the next launch, there are no errors, there are docks, the variables are taken without problems ....
And what's wrong with the first time then?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2021-02-25
@Zimaell

Is this the code in the editor being executed? Most likely Resources needs to be reloaded/updated. There is something like AssetsDatabase.Reload (written from the bulldozer - google the first word).
If this code is not in the editor, then this cannot be done.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question