- Home /
[HELP]GetString is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead
I want to use the name1 variable in all my scripts, so i stored it using PlayerPrefs.SetString. It gives the following error when i use it in one of my javascript:
GetString is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead
I tried to use it in start() too but the problem remains the same. Well, I am not sure if the error is because of this but I have all my scripts in C# but one in javascript as it doesn't give any such error in my C# script. So, can I access the variable using PlayerPrefs.GetString in javascript when i have set it in C#? Please help me solve the error.
here is the link for my code. https://gist.github.com/anonymous/d03e6c18729f5e44680ee271e1b70dc1/revisions
I am a new to unity and to both C# and javascript and I am learning it on my own. So, that causes the trouble and that's the reason for the switch between the two languages. Sorry for being so silly.
Answer by Vicarian · Jul 27, 2017 at 04:38 PM
I've converted your script to C#. You do not need to learn both JavaScript and C# to work with Unity, and C# scripts are far easier to use.
using System.IO;
using UnityEngine.UI;
public class Timer : MonoBehaviour {
static int numberOfCheckPointsCrossed = 0;
private string pathOfFile;
private string fakeName;
static float countDown = 240.0f;
// This hasn't been assigned. Without knowing anything about your Hierarchy,
// I don't know how to assign it.
Text counter;
void Start() {
fakeName = PlayerPrefs.GetString ("name1");
pathOfFile = "F:/Drishti/Data/Phase2/" + fakeName + ".txt";
}
void OnTriggerEnter(Collider col) {
numberOfCheckPointsCrossed++;
Destroy(gameObject);
}
void Update() {
countDown -= Time.deltaTime;
count = Mathf.RoundToInt (countDown);
counter.text = "" + count.ToString ();
if (countDown <= 0 || gameObject.tag == "Ca")
{
Application.LoadLevel("Up view");
StreamWriter sw = new StreamWriter(pathOfFile);
sw.WriteLine ("number of checkpoints crossed: " + numberOfCheckPointsCrossed);
sw.flush();
sw.Close();
}
}
}
Comment if your error isn't resolved by this port.
Thank you for converting my Script to C#. the error disappeared once I restarted the Unity. But there is one more problem in my code,as in the above code, when I append my file in Update function
if (countDown <= 0 || gameObject.tag == "Ca")
{
StreamWriter sw = new StreamWriter(pathOfFile, append:true);
sw.WriteLine ("number of checkpoints crossed: " + numberOfCheckPointsCrossed);
} It would append the same value multiple times in the file.
][1]
Your answer
Follow this Question
Related Questions
No Monobehaviour scripts in files 1 Answer
I can't add my script to a boss 2 Answers
unity script error 1 Answer