- Home /
Converting scripts between javascript and c#
Hi, I try to rewrite js controller script in C Sharp. In my js file I've many classes whose only storing some variables. Similar construction won't work in C#, because those variables are unreachable. For example
js
class Aaa{
var abc = 1.5;
}
var d:Aaa;
in c# i try this
class Aaa{
public float abc = 1.5f;
}
public Aaa d = new Aaa();
d.abc = <new value>
This construct give me NullReferenceException. Where I've made mistake?
Answer by zharik86 · Nov 13, 2014 at 07:57 PM
Try this:
public class Aaa { //add "public" modificator, without variable/class is "private"
public float abc = 1.5f;
}
public Aaa d = new Aaa();
void Start() {
d.abc = 2.0f;
}
Initialization your variable of class in Awake() or Start(). I hope that it will help you.
Thanks for respond :) I set this classes with all vars to public but seems that this construct won't work also. This is quite strange for me because this code is quite simple
public class SomeClass:$$anonymous$$onoBehavior {
public class Aaa() {
public float abc =1.5f;
}
public Aaa d; // with = new Aaa() unity throw me StackOverflowException :)
void Start() { //or Awake
d.abc <---- at this level even Debug.Log give me NullReferenceException
}
}
Im stuck with this, and don't know how reach this variables. Dosn't matter is this float vector or bool I can't set or get this value 8-(
@b2prezmo Correct create your class:
public class Aaa() { //wrong, delete "()"
And see my example. For me all works.
Answer by Jeff-Kesselman · Nov 13, 2014 at 08:27 PM
Your problem is that your code is recursively constructing...
Your class Aaa has a field d which is initialized by constructing a new Aaa,
the new Aaa has a field d which is initialized by constructing another Aaa,
that has a field d which is initialized by constructing another Aaa....
And it goes on forever, but since computer are finite, it eventually runs out of stack room and crashes.
I've noticed that, but I wonder how can it be: in js all code works fine, but similar construct in C won't work. Unity don't throw stackoverflow error if declaration is simple : public Aaa d; ins$$anonymous$$d public Aaa d = new Aaa(). Besides this, script stop at Awake or Start function where I try to get some variables from this classes.
Your answer
Follow this Question
Related Questions
Need help converting js to C# 1 Answer
How to fix this for c#? 1 Answer
C# score not updating 1 Answer
Type `GUIText' does not contain a definition for `text' 2 Answers