- Home /
array of objects
I want to save a string (word) and int (score) into an array and then sort based on the int.
Im using Javascript. I've tried making a class then saving an object in the array:
public class wordClass
{
var word : String;
var score : int;
}
var wordObject = wordClass();
wordObject.word = wordString;
wordObject.score = wordScore;
PermanentVariables.wordsFound.push(wordObject);
Debug.Log("CLASS TEST: " + PermanentVariables.wordsFound[1].word);
//PermanentVariables are is where the array is stored. I made this so that I can access these from any scene
public static class PermanentVariables
{
public var wordsFound = new Array();
public var gameScore : int;
public var levelScore : int;
}
I get the error: Assets/Scripts/GameScript.js(112,77): BCE0019: 'word' is not a member of 'Object'.
Is there a better way to do this? I haven't written the sort code yet.
Answer by Chronos-L · Apr 15, 2013 at 01:56 AM
Please read this. Javascript array is untyped, so if you want type-specific operation, you need to do type-casting:
Debug.Log("CLASS TEST: " + (PermanentVariables.wordsFound[1] as wordClass).word);
Why don't you use the .NET's List< T >
instead; the only thing Javascript array can do but the List< T >
can't is to store different types of variable, which is not needed at all in your case.
If I declare the variables in the wordClass class without specifying a type I get the same error. I imagine I'd get the same error no matter what array type I use? maybe not?
you can use a Dictionary too
// declaration
var myDict = new Dictionary.<int,String>();
// insert a value for the given key
myDict[any$$anonymous$$ey] = newValue;
// retrieve a value
var thisValue = myDict[any$$anonymous$$ey];
You can put a #pragma strict
in the first line of your script, it will make you write you script in a stricter/explicit syntax.
@jitesh's solution is good as well; From your code, I think that you are making a scramble/word-guessing game, using a Dictionary
is a viable alternative. However, I would suggest you to use Dictionary. < string, int >()
ins$$anonymous$$d.
Use Dictionary< string, int >()
ins$$anonymous$$d, the string
will become the key, i don't think you will have 2 different score for the same string
right? So use string
for the key, and int
as the value/score.
the only thing Javascript array can do but the List can't is to store different types of variable
Actually you can store different types of variables in a List by using List.< Object >
, though you then have the same casting issues that you have with Array. Although the List is still faster. And yes that makes JS Array completely useless. ;)
Your answer
Follow this Question
Related Questions
adding classes to arrays 2 Answers
What are GameTiles? 1 Answer
Instantiating objects from a class? (C#) 1 Answer
Cannot edit values of Class when created using .JSON file 1 Answer