x


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

more ▼

asked Jul 10 '10 at 09:22 AM

SoloChristian gravatar image

SoloChristian
142 10 11 14

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.

Sep 04 '10 at 05:11 PM Maltus
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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. :)

more ▼

answered Jul 10 '10 at 09:32 AM

qJake gravatar image

qJake
11.6k 43 78 161

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3570
x372

asked: Jul 10 '10 at 09:22 AM

Seen: 2545 times

Last Updated: Jul 10 '10 at 09:42 AM