Array of GameObjects Android/iPhone - call/typing/casting problem?

Hi all,

Ok, i've had problems before with typing and casting, and today is no exception.

I've tried using generic casting to make this work on mobile (it works as as on PC, but not on mobile)...

script was;

var MenuItems : GameObject [];

function OnGui () {

//cut some code

if ( GUI.Button ( Rect(ButtonMargin + ((Screen.width - ButtonMargin)/MenuItems.length) * MenuIndex ,Screen.height - ButtonHeightOffset - ButtonMargin,(Screen.width - ButtonMargin * 2)/MenuItems.length - ButtonMargin,ButtonHeight ), MenuItems[MenuIndex].GetComponent("MenuItem").MenuItemName ) )

//cut some code

}

i got an error - MenuItemName is not a member of UnityEngine.Component..

I change;

`MenuItems[MenuIndex].GetComponent("MenuItem").MenuItemName` to `MenuItems[MenuIndex].GetComponent.().MenuItemName`

but then i get - Unity.MenuItem must derive from UnityEngine.Component in order to substitute generic parameter T in UnityEngine.GameObject.GetComponent()

Like i always say, if this is a simple thing which i know it is, a hand in the right direction instead of the answer is always the best answer, otherwise i still appreciate any help given (answer given, lol!)

Thank you guys again.

Hey Matty

A way around this in JavaScript is to assign your component to a variable of the Type you want. So for your case above, try this:

var menuItem : MenuItem;
menuItem = MenuItems[MenuIndex].GetComponent(MenuItem);

Then you can just use that variable in your function call:

menuItem.MenuItemName;

The generic type call you attempted to change it to's syntax is actually:

MenuItems[MenuIndex].GetComponent<MenuItem>().MenuItemName // No . before the <>

but this is C# only.

I hope this helps you out. I'm a C# programmer myself, so my JS isn't all that confident =P

Wait, is MenuItem your own Component, or are you referring to the Unity3D MenuItem class?

If you are referring to your own component, first possibility I see is that the namespace is clashing. MenuItem is already used by Unity3D engine, so perhaps you want to use another name for your component.

If you want to refer to the Unity3D's MenuItem class, then you are getting the error because MenuItem is not a component. There are two ways of casting in C#:

MenuItem m = (genericObject) as MenuItem

Or

MenuItem m = (MenuItem)genericObject

More info on how those two methods differ can be found here.

If you are referring to your own component, first possibility I see is that the namespace is clashing. MenuItem is already used by Unity3D engine, so perhaps you want to use another name for your component.