- Home /
Singleton Error with code
Here is my MySingleton.js javascript with code.I am getting errors mentioned at bottom of code.Need a Score var to be updated in other class where i am accessing it.Please don't mind my stupidity in code as am a newbie....:)Thanks in advance.
public class MySingleton { private static MySingleton instance;
public MySingleton () { if (instance != null) { Debug.LogError ("Cannot have two instances of singleton. Self destruction in 3..."); return; }
instance = this;
}
public static MySingleton Instance { get { if (instance == null) { new MySingleton (); }
return instance;
}
}
private int score;
public int Score { get { return score; } set { score = value; } }
}
And the Error I am getting is:Assets/Test/MySingleton.js(3,20): BCE0043: Unexpected token: MySingleton.
Assets/Test/MySingleton.js(5,12): BCE0043: Unexpected token: MySingleton.
Assets/Test/MySingleton.js(5,24): BCE0044: expecting EOF, found '('.
I'm no javascript guy (so I may be wrong), but isn't there a "class" missing in your class declaration?
Not exactly an answer, but you may want to use C# for the singleton, if only because of this: http://answers.unity3d.com/questions/45879/can-i-declare-properties-in-js
@Jake L:The line at the top of the box has the class declaration ,i don't know why was it not taken as part of code by the community server.
@TheDemiurge:Ummm..i couldn't get that code.An answer in javascript would be helpful for the newbie.Still thanks for your effort.
Answer by Jean-Fabre · Apr 18, 2011 at 10:28 AM
Hi,
Here is the full script you need to have:
make sure you create a c sharp script, cause this is csharp, not javascript. And make sure you name the script the same as the classe you define so your script file in your project must be named MySingleton.
using UnityEngine;
public class MySingleton {
private static MySingleton instance;
public MySingleton ()
{
if (instance != null)
{
Debug.LogError ("Cannot have two instances of singleton. Self destruction in 3...");
return;
}
instance = this;
}
public static MySingleton Instance
{
get
{
if (instance == null)
{
new MySingleton ();
}
return instance;
}
}
private int score;
public int Score
{
get
{
return score;
}
set
{
score = value;
}
}
}
Bye,
Jean
Thanks but Isn't the same code i have done in there??Will let you know when i try it out,Thanks by the way:)
Yes, but you save it as a javascript, and you should create a c# script ins$$anonymous$$d and copy that content. It won't work as a javascript code.
And also, I have added the include command ( first line ) otherwise you will get errors as well.
Your answer
Follow this Question
Related Questions
error message for var 1 Answer
scripting colliders errors 1 Answer
Trying to Destroy Object when Wave starts 1 Answer
Null reference exception - singletone 0 Answers