- Home /
Getting C# to access a javascript global Array and Components
I'm trying to finally learn C# and am trying to get a script to access an global Java array.
The array has GameObjects in it and is in the plug-ins folder so it compiles first. And I'm trying basically to convert this java code to C# so I can use an Inventory System I've already made in Java Script with my GUI that I made in C#.
tmpTexture = (GLOBALZ.objectsInWeapons[(4 * rows) + colmn].GetComponent(ObjectInfo).iconTexture);
//set the object's texture
Basically all the game objects have a scripts attached called "ObjectInfo" that stores their icon.
I have no idea how to do this after 2 days of trying.
Thanks for any help.
Christian
I am trying to learn the nuances of c# too as their is much cool stuff you can do. I mean I too love Unitys version of JS and love its speed.
Answer by qJake · Jul 10, 2010 at 09:32 AM
It took you two days to figure this out? ... You might want to read this:
http://answers.unity3d.com/questions/5507/what-are-the-syntax-differences-in-c-and-javascript
It should clear up a lot of confusion you might have.
As for your code, C# won't implicitly cast from Component
to your own class, ObjectInfo
. You need to explicitly cast it, and personally, my favorite way is with the as
keyword. You also need to specify the type with GetComponent()
(because GetComponent()
's parameter is a Type
, so you need to use typeof()
), although there are other ways of using GetComponent()
, this is my favorite way).
tmpTexture = (GLOBALZ.objectsInWeapons[(4 * rows) + colmn].GetComponent(typeof(ObjectInfo)) as ObjectInfo).iconTexture;
Although that is an extraordinarily ugly line of code. I would make it neater:
GameObject tmpObject = GLOBALZ.objectsInWeapons[(4 * rows) + colmn]; ObjectInfo tmpInfo = tmpObject.GetComponent(typeof(ObjectInfo)) as ObjectInfo;
if(tmpInfo == null) { // Couldn't retrieve the "ObjectInfo" script here. } else { tmpTexture = tmpInfo.iconTexture; }
See? Much, much easier to read and understand. :)