Help writing to a file every update/frame (JS)

Hello all,

Here is my code, I wish to save and overwrite an integer variable every frame to a file. (JS)

import System;
import System.IO;

var targetScript: Dupe;
var fileName = "MyFile.txt";

function Start()
        if (File.Exists(fileName))
            Debug.Log(fileName+" already exists.");
        var sr = File.CreateText(fileName);
        targetScript.oofs -= 0;
function Update(){
	sr.WriteLine (targetScript.oofs);

The error I get is telling me that “sr” is an unknown identifier, probably because the functions are separated and when I try to combine the functions that throws up a missing semicolon error and an unexpected token. I don’t know if there is a way that I can get the variable to be identified by using a static variable but I have already tried doing things along those lines and I can’t get it to work.

I would appreciate any help very much.

Thanks in advance.

If you define your variable sr of type var in start it’s a local variable that is not available outside of the start function so if you try to use it inside of update it says it does not know a variable of name sr.

Define the variable inside the class like you did with “fileName” if you want to make this work.