This is a little trick I picked up from another game engine, but I can’t get it to work in unity,
I want to define a structure so I can access the data stored in a variable by name.
What I’ve done before is something like this
function myStruct(foo, bar) {
this.foo = foo;
this.bar = bar;
}
var myData = new myStruct("a", "b");
.
.
.
print(myData.foo);
print(myData.bar);
This would print “a” and “b”
This doesn’t appear to work in unity, I get an error saying “foo is not a member of” followed by the name of the script it is in. So it seems “.this” points to the script not the function. Is that right, is there another way to do this in unity?
class myStruct {
var foo : String;
var bar : String;
}
var myData = new myStruct();
myData.foo = "a";
myData.bar = "b";
print(myData.foo);
print(myData.bar);
You can make a constructor if you want to assign values when initializing:
class myStruct {
var foo : String;
var bar : String;
function myStruct (s1 : String, s2 : String) {
foo = s1;
bar = s2;
}
}
function Start () {
var myData = new myStruct("a", "b");
print(myData.foo);
print(myData.bar);
}
You can define classes in javascript but no structs. Classes are, however, passed by reference and if you ever want to make a copy of an object you’ll have to implement a clone method yourself.
Depending on what you want to do, that might be what you want.
You can however define structs in Boo or C# and then use them in Javascript.
@Jessy
You have to define a ToString() method that returns a string. Whenever you print an object the result of that method will be displayed.
Is there anything special you need to do to get that to work. When I tried mixing C# and Javascript before there were some issues with the order they were compiled.
How do you make the structure globally available?
Yes, the compilation order is important. You can read more here:
You have to make sure that the Boo and C# scripts you want to access are compiled before your javascript file.
What you cannot do, like this, are two scripts of different languages each depending on the other. Though I believe this could be solved in most cases with restructuring or interfaces.