Convert object[] to GUIContent[] in C# How??????

ArrayList Listy = new ArrayList();
Listy.Add(new GUIContent("A string", "A tooltip"));
Listy.Add(new GUIContent("A string2", "A tooltip2"));
Listy.Add(new GUIContent("A string3", "A tooltip3"));

GUIContent[] myContent = Listy.ToArray(GUIContent);
/*This throws a cannot convert 'object[]'  to UnityEngine.GUIContent[]'. Are you missing a cast?*/

I know this is possible in Javascript. What am I doing wrong? Whats the proper way to do this in c#??

Well, the error gives you a hint (a solution, actually) :slight_smile: You just need to typecast it to the right type:

GUIContent[] myContent = (GUIContent[])Listy.ToArray(GUIContent);

This should work.

The tip above is not really working.
C# is strictly typed and unlike JS, you need to cast “content” of a list to a certain type before you use it as such.

You could make Listy a list of GUIContent by using:

using UnityEngine;
using System.Collections.Generic;

public class Test : MonoBehaviour {

// Use this for initialization
void Start () {
List Listy = new List();
Listy.Add(new GUIContent(“A string”, “A tooltip”));
Listy[0].tooltip = “lala”;
//…

The list you used does not require anything than an object in it. So you can use it’s content only as object. If you know it’s something else, you can cast any item before using it:

GUIContent gc = (GUIContent)Listy[0];
gc.tooltip = “lala”;

Or you can cast a reference (which is a reference to an array) :slight_smile: Passing a type of GUIContent to the ToArray() method, converts the type of the elements, but you still need to typecast the reference of the whole array. That is why it works. Of course, you can also use a List, but this also works for me (I also added “typeof()”, because it seemed to be needed):

GUIContent[] myContent = (GUIContent[])Listy.ToArray(typeof(GUIContent));

Yes using typeof like that gets the conversion going. Very nice.

List Listy = new List();
I like this method thou it seems cleaner.

Thanks Guys