Unity - my array is not updating its elements - arrays

I'm making my first app in Unity to learn English words and I got stuck.
I created and array like that:
public string[] words = {
"apple",
"banana",
"big",
"blue",
"book",
"one",
"two"
};
I'm using PlayerPrefs to save which array element I'm learning at the moment.
The problem is that I can't add or remove elements from this array. Whatever I do it always shows these 7 elements.
Can you please tell me why?
The thing is I don't want to add elements dynamically or within the script. I just want to expand my array manually by adding more elements, like this:
public string[] words = {
"apple",
"banana",
"big",
"blue",
"book",
"one",
"two",
"colours",
"green",
"orange",
"pencil",
"yellow",
"four",
"five",
"six",
"small",
};
The thing is that after changing array from my first post to this one, change takes no effect. Program still sees only 7 elements.
I tried to delete some elements and the result is the same. It looks like the program holds my array in memory or something....
Here is my complete code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
public static GameManager instance;
public bool isLearnOn;
public bool isFrontMenuActive;
public GameObject frontMenuEmpty;
Animator frontMenu;
Animator finishPanel;
//Tasks Elements
Image taskImage;
GameObject taskImageEmpty;
GameObject taskAllElementsEmpty;
GameObject taskTextEmpty;
Text taskText;
InputField taskInputField;
AudioSource taskAudio;
int randomWord;
int wordCount;
int allWordsCount;
int collectPoint;
Text pointsBoard;
Text hint;
public bool isHintShown;
GameObject hintTextEmpty;
int innerTaskCount;
public bool isFinishPanelOn;
void Awake(){
if (instance == null) {
instance = this;
}
}
void Start () {
collectPoint = (PlayerPrefs.GetInt ("points"));
isLearnOn = false;
//Variable assignment
//Tasks Elements
taskAllElementsEmpty = GameObject.Find ("TaskAllElementsEmpty");
taskImage = GameObject.Find ("TaskImage").GetComponent <Image>();
taskTextEmpty = GameObject.Find ("TaskTextEmpty");
taskText = GameObject.Find ("TaskText").GetComponent <Text>();
taskInputField = GameObject.Find ("TaskInputField").GetComponent <InputField>();
taskAudio = GameObject.Find ("GameManager").GetComponent <AudioSource>();
pointsBoard = GameObject.Find ("PointsBoard").GetComponent <Text>();
hint = GameObject.Find ("Hint").GetComponent <Text>();
hintTextEmpty = GameObject.Find ("HintTextEmpty");
finishPanel = GameObject.Find ("FinishPanel").GetComponent <Animator>();
taskImageEmpty = GameObject.Find ("TaskImageEmpty");
frontMenuEmpty = GameObject.Find ("FrontMenuEmpty");
frontMenu = GameObject.Find ("FrontMenuEmpty").GetComponent <Animator>();
pointsBoard.text = collectPoint.ToString ();
allWordsCount = words.Length;
Debug.Log (allWordsCount);
isFrontMenuActive = false;
FrontMenuShowHide ();
taskAllElementsEmpty.SetActive (false);
isHintShown = false;
hint.text = "";
innerTaskCount = 0;
isFinishPanelOn = false;
//TODO Disable finisih panel
}
void Update () {
if (isLearnOn == true) {
if (wordCount < allWordsCount) {
if ((taskInputField.text == words [wordCount]) && innerTaskCount == 0) {
Task1 ();
taskText.text = "";
taskInputField.placeholder.GetComponent<Text>().text = "What is it?";
innerTaskCount = 1;
}
else if ((taskInputField.text == words [wordCount]) && innerTaskCount == 1) {
Task1 ();
taskText.text = "";
taskInputField.placeholder.GetComponent<Text>().text = "Listen and type the word down";
taskImageEmpty.SetActive (false);
innerTaskCount = 2;
}
else if ((taskInputField.text == words [wordCount]) && innerTaskCount == 2){
if (isHintShown == false) {
CollectPoints ();
NextTask ();
Debug.Log (wordCount);
innerTaskCount = 0;
} else {
NextTask ();
innerTaskCount = 0;
}
}
} else {
if(isFinishPanelOn == false){
HideFinishPanel ();
wordCount = 0;
}
}
} else {
if (taskInputField.text == words [randomWord]) {
if (isHintShown == false) {
CollectPoints ();
RandomTask ();
} else {
RandomTask ();
}
}
}
}
public void FrontMenuShowHide(){
if (isFrontMenuActive == true) {
frontMenu.Play ("FrontMenuOut");
isFrontMenuActive = false;
} else {
frontMenu.Play ("FrontMenu");
isFrontMenuActive = true;
}
}
public void Task1(){
isHintShown = false;
wordCount = (PlayerPrefs.GetInt ("wordCountPrefs"));
taskAllElementsEmpty.SetActive (true);
taskText.text = words[wordCount];
taskInputField.text = "";
taskInputField.ActivateInputField ();
//SoundPlay ();
LoadPicture ();
taskTextEmpty.SetActive (true);
hint.text = "";
taskInputField.placeholder.GetComponent<Text>().text = "Copy the word, please...";
string path = "audio/" + words [wordCount];
taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
taskAudio.Play ();
taskImageEmpty.SetActive (true);
}
public void RandomTask(){
isHintShown = false;
randomWord = Random.Range (0, allWordsCount);
taskAllElementsEmpty.SetActive (true);
taskText.text = words[randomWord];
taskInputField.text = "";
taskInputField.ActivateInputField ();
//SoundPlay ();
LoadRandomPicture ();
taskTextEmpty.SetActive (false);
hint.text = "";
taskImageEmpty.SetActive (true);
taskInputField.placeholder.GetComponent<Text>().text = "What is it?";
string path = "audio/" + words [randomWord];
taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
taskAudio.Play ();
}
public void SoundPlay(){
if (isLearnOn == true) {
string path = "audio/" + words [wordCount];
taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
taskAudio.Play ();
} else {
string path = "audio/" + words [randomWord];
taskAudio.clip = (AudioClip)Resources.Load(path, typeof(AudioClip));
taskAudio.Play ();
}
}
public void LoadPicture(){
string path = "img/" + words [wordCount];
taskImage.sprite = (Sprite)Resources.Load(path, typeof(Sprite));
}
public void LoadRandomPicture(){
string path = "img/" + words [randomWord];
taskImage.sprite = (Sprite)Resources.Load(path, typeof(Sprite));
}
public void NextTask(){
wordCount++;
PlayerPrefs.SetInt ("wordCountPrefs", wordCount);
Task1 ();
}
public void LearnIsOn(){
isLearnOn = true;
}
public void LearnIsOff(){
isLearnOn = false;
}
public void CollectPoints(){
collectPoint++;
PlayerPrefs.SetInt ("points", collectPoint);
pointsBoard.text = collectPoint.ToString ();
}
public void ShowHint(){
if (isLearnOn == true ) {
if (innerTaskCount != 0){
hint.text = words [wordCount];
isHintShown = true;
}
} else {
hint.text = words [randomWord];
isHintShown = true;
}
}
public void HideFinishPanel(){
if (isFinishPanelOn == true) {
finishPanel.Play ("FinishPanelOut");
isFinishPanelOn = false;
} else {
finishPanel.Play ("FinishPanel");
isFinishPanelOn = true;
}
}
public string[] words = {
"apple",
"banana",
"big",
"blue",
"book",
"one",
"two",
"colours",
"green",
"orange",
"pencil",
"yellow",
"four",
"five",
"six",
"small",
};
}
`

This happens because Unity initialize serialized public objects itself. When you define your variable first time in script if you initialized it manually, Unity serialize it with your values. Else Unity serialize it with default values.
For example. When you create the script below first time like;
public class GameManager : MonoBehaviour {
public string[] words = {
"one",
"two",
"three",
"four",
"five",
"six",
};
}
Unity serialize words with this values. After that even if you change initial values from script, next time you run, it actually doesn't change.
For this, there are two options. First; define your variable in script with [System.NonSerialized] attribute.
[System.NonSerialized] public string[] words = {};
Second choice, select the gameobject from hierarchy. On inspector, chose your scripts component and Reset it when you change initial variables.

You need to use list in place of array. List allows you to add or delete any item.
List <string> names = new List<string>();
Void Start()
{
names.Add(“apple”);
}

If you want to be able to do both, adding elements in the editor and by script you should rather use a List<string> words and check if the value already exists in the list before adding it in the script:
[SerializeField]
private List<string> words = new List<string>();
private void Start(){
if(!words.Contains("apple")){
words.Add("apple")
}
if(!words.Contains("banana")){
words.Add("banana")
}
}
Independent from that, if you want to update the List/Array also within the Editor I recomend you use the [ContextMenu] tag:
e.g. for your array:
public string[] words; // you don't set it here but expect it to be set in the editor
[ContextMenu("Import scripted array")]
private void ImportScriptedArray(){
// Note in this case I simply overwrite any setting within the editor
// There are multiple ways to prevent this like before using List or other methods
words = new [] {
"bla",
"bli",
"blub"
};
}
This adds the method ImportScriptedArray to the context menu of this component in the editor. So first you have this unset array:
On your script/component you now can click on the settings icon to open the context menu.
And in the context menu click on your just generated Import Scripted Array to import your array from the script.

Related

System.IndexOutOfRangeException in c# window form

I have been trying too parse 2 parameter using for loop but it only loop once and locates one parameter. This is my code.
By providing rectangle 70,80 command in the form, I am trying to draw shapes but while passing through check variable for loop works only once. It does not increments but returns value only after first execution then goes to check number of parameter then rejects with error Array out of bounds.
public String[] ParameterSplit;
public IDictionary<string, int> VariableDictionary = new Dictionary<string, int>();
public IDictionary<string, int> MethodVariableDictionary = new Dictionary<string, int>();
public Boolean AlreadyInArray = false;
public Boolean Value1IsVariable = false;
public Boolean Value2IsVariable = false;
public int value = 0;
public int value1 = 0;
public int value2 = 0;
public CommandParser()
{
}
//This method is used for the validation of commands and parameters which passes thorough
//singleline command and multiline command method
public string[] CommandParsers(string input, int lineCount)
{
string[] text = { };
string[] inputcommand = input.Split(',', ' ');
if (inputcommand[0].ToUpper() == "MOVETO")
{
if(inputcommand.Length < 4)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
}
else
{
if (inputcommand[0].ToUpper() == "DRAWTO")
{
if (inputcommand.Length == 3)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
else
{
MessageBox.Show($"ERROR: Provide correct parameter for moveto in line no {lineCount}");
string[] strings = { "moveto,100,100" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "RECTANGLE")
{
ParameterSplit = inputcommand[1].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
CheckForVariable();
if (ParameterSplit.Length == 2)
{
}
else
{
Convert.ToInt32(ParameterSplit[0]);
Convert.ToInt32(ParameterSplit[1]);
text = ParameterSplit;
}
}
else if (inputcommand[0].ToUpper() == "CIRCLE")
{
if (inputcommand.Length == 2)
{
Convert.ToInt32(inputcommand[1]);
text = inputcommand;
}
else
{
MessageBox.Show("ERROR: Provide correct parameter for circle in line no " + lineCount );
string[] strings = { "circle,20" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "TRIANGLE")
{
if (inputcommand.Length == 3)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
else
{
MessageBox.Show("ERROR: Provide correct parameter for triangle in line no "+ lineCount);
string[] strings = { "triangle,20,60" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "PEN")
{
Pen = true;
string[] validateinput = { "pen", inputcommand[1] };
text = validateinput;
switch (inputcommand[1])
{
case "red":
color = Color.Red;
break;
case "blue":
color = Color.Blue;
break;
case "yellow":
color = Color.Yellow;
break;
case "green":
color = Color.Green;
break;
case "violet":
color = Color.Violet;
break;
}
}
else if (inputcommand[0].ToUpper() == "FILL")
{
string[] validateinput = { "fill", inputcommand[1] };
text = validateinput;
switch (inputcommand[1])
{
case "on":
fill = true;
break;
case "off":
fill = false;
break;
}
}
else if (inputcommand.Length > 2)
{
text = inputcommand;
//checks if the middle element is a "="
if(inputcommand[1].ToUpper() == "=")
{
//check if the variable is already stored or not
//StoreVarialable();
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if (variable.Key.Equals(inputcommand[0]))
{
AlreadyInArray = true;
}
}
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if(variable.Key.Equals(inputcommand[2]))
{
value1 = variable.Value;
Value1IsVariable = true;
}
}
if(inputcommand.Length.Equals(5))
{
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if (variable.Key.Equals(inputcommand[4]))
{
value2 = variable.Value;
Value2IsVariable = true;
}
}
if (AlreadyInArray)
{
VariableDictionary.Remove(inputcommand[0]);
}
}
try
{
if (Value1IsVariable.Equals(false))
{
value1 = Convert.ToInt32(inputcommand[2]);
}
if (Value2IsVariable.Equals(false))
{
if (inputcommand.Length.Equals(5))
{
value2 = Convert.ToInt32(inputcommand[4]);
}
}
if (inputcommand.Length > 3)
{
if (inputcommand[3].Equals("+"))
{
value = value1 + value2;
}
else if (inputcommand[3].Equals("-"))
{
value = value1 - value2;
}
else
{
//InvalidOperator();
}
}
else
{
try
{
value = int.Parse(inputcommand[2]);
}
catch (FormatException ex)
{
//If it is not an integer throw an error
//ValueIsIncorrect();
}
}
//Adds the variable with the inputted value if it is an integer
// VariableDictionary.Add(inputcommand[0], value);
}
catch (FormatException ex)
{
//If it is not an integer throw an error
//ValueIsIncorrect();
//return;
}
}
else
{
}
}
else
{
string[] validateinput = { "error" };
text = validateinput;
}
//end of condition
}
return text;
}
public void CheckForVariable()
{
//Loops through all the parameters
for (int i = 0; i<ParameterSplit.Length ; i++)
{
int index = i;
try
{
//Checks if the parameter is an int
int test = int.Parse(ParameterSplit[index]);
}
catch
{
Boolean foundVariable = false;
foreach (KeyValuePair<string, int> variable in MethodVariableDictionary)
{
if (variable.Key.Equals(ParameterSplit[index]))
{
//if it is then assign the parameter the integer value of the variable
ParameterSplit[index] = variable.Value.ToString();
//ErrorList = ErrorList + variable.Key + ParameterSplit[i] + Environment.NewLine; ;
foundVariable = true;
}
}
if (foundVariable == false)
{
//if it is not then loop through the VariableDictionary to check if the parameter is a variable name
foreach (KeyValuePair<string, int> variable in VariableDictionary)
{
if (variable.Key.Equals(ParameterSplit[i]))
{
//if it is then assign the parameter the integer value of the variable
ParameterSplit[i] = variable.Value.ToString();
}
}
}
}
}
}
//This method is used to get the color from pen by returning its values
internal Color getColor()
{
return color;
}
}
I tried this where I have to check 2 parameter using for loop inside CheckForVariable method

Unity3D: How to go Back or Forward in Array list

I have a gameObject with an ID, the gameObjects are spawned by giving initial ID: 1 , then any after spawned will be +1 so next is ID: 2.
I have two buttons that check current gameObjects ID#, BackOneButton (-1) and PlusOneButton (+1).
Currently it works but only if the array of gameObjects have IDs in order like for example [gameObject-ID:1], [gameObject-ID:2], [gameObject-ID:3]
But since you can self destruct a certain gameObject, here is where the error is --->
Now the array is not in order for example [gameObject-ID:1], [gameObject-ID:3], [gameObject-ID:4]. So if I'm currently in [gameObject-ID:3] and I use the BackOneButton and looks for ID: 2 it won't find it BUT there is ID:1. That's my error, I can't seem to figure out how to handle this.
Basically, How do I handle missing increments and skip over the missing?
Left Button (MinusOneButton)
void ButtonAction_LeftMinusOne()
{
// Get list of all gameObjects and -1 current to switch
string objName = manager.currentObjectTransform.name;
string[] splitArray = objName.Split('_');
string idObjNumber = splitArray[1];
switch (idObjNumber)
{
case "0":
// not supposed to be ID: 0
break;
case "1":
// nothing to go back to, this is ID: 1
break;
default:
// currently in (ID: 2 & Up) second object
int currentID = int.Parse(idObjNumber);
string idBackOne = (currentID - 1).ToString();
GameObject[] allObjInFull = GameObject.FindGameObjectsWithTag("Object");
if (allObjInFull.Length >= 2)
{
for (int i = 0; i < allObjInFull.Length; i++)
{
if (allObjInFull[i].transform.name.Contains(idBackOne))
{
// Set Camera
camera.transform.parent = allObjInFull[i].transform.GetChild(0).GetChild(1);
camera.transform.position = allObjInFull[i].transform.GetChild(0).GetChild(1).position;
camera.transform.rotation = allObjInFull[i].transform.GetChild(0).GetChild(1).rotation;
}
}
}
break;
}
}
Right Button (PlusOneButton)
void ButtonAction_RightPlusOne()
{
// Get list of all objects and +1 current to switch
string objName = manager.currentObjectTransform.name;
string[] splitArray = objName.Split('_');
string idObjNumber = splitArray[1];
switch (idObjNumber)
{
case "0":
// not supposed to be ID: 0
break;
default:
// currently in (ID: 1 & Up) object
int currentID = int.Parse(idObjNumber);
string idPlusOne = (currentID + 1).ToString();
GameObject[] allObjInFull = GameObject.FindGameObjectsWithTag("Object");
if (allObjInFull.Length >= 2)
{
for (int i = 0; i < allObjInFull.Length; i++)
{
if (allObjInFull[i].transform.name.Contains(idPlusOne))
{
// Set Camera
camera.transform.parent = allObjInFull[i].transform.GetChild(0).GetChild(1);
camera.transform.position = allObjInFull[i].transform.GetChild(0).GetChild(1).position;
camera.transform.rotation = allObjInFull[i].transform.GetChild(0).GetChild(1).rotation;
}
}
}
break;
}
}
It would be way better (especially regarding maintenance) and more efficient to have a central manager class with a List<GameObject> where you simply Add and Remove items dynamically. (Since you already seem to have one in manager I would rather extend that one)
public static class ObjectsManager
{
// If you are not concerned about
// capsulation you could ofcourse make this public as well
// but I thought this is cleaner
private static List<GameObject> objects;
// Read-only property
public static int Count
{
get
{
Initialize();
return objects.Count;
}
}
// initialize the list once
// I first had this in e.g. Awake
// but now you can easily use this in multiple scenes
public static void Initialize(bool force reinitialize = false)
{
if(objects != null && ! reinitialize) return;
objects = FindObjectsWithTag("Object").ToList();
}
public static void Add(GameObject newObject)
{
Initialize();
if(objects.Contains(newObject) return;
objects.Add(newObject);
}
public static void Destroy(GameObject toDestroy)
{
Initialize();
if(objects.Contains(toDestroy)
{
objects.Remove(toDestroy);
}
Object.Destroy(toDestroy);
}
public static int IndexOf(GameObject obj)
{
Initialize();
return objects.IndexOf(obj);
}
public static GameObject GetByIndex(int index)
{
Initialize();
// Use modulo to wrap around the index in case
// +1 or -1 exceeds the list ends
// in your case you might not need it
// but I decided to add it to be more flexible
var nextIndex = (index + 1) % objects.Count;
return objects[index];
}
}
Everytime you Instantiate a new object make sure to also call
ObjectsManager.Add(newObject);
and everytime where you destroy an object rather use
ObjectsManager.Destroy(objectToDestroy);
so it is also removed from the list first.
Then you can easily use
var currentIndex = ObjectsManager.IndexOf(certainObject);
to get the current index of an object and simply move through the index (+1, -1)
var nextObject = ObjectsManager.GetByIndex(currentIndex + 1);
var lastObject = Objects manager.GetByIndex(currentIndex - 1);
In case you switch the scene you have reinitialize the list once in order to get rid of null references
ObjectsManager.Initialize(true);
In your example code you would e.g. use something like
void ButtonAction_LeftMinusOne()
{
GameObject currentObject = manager.currentObjectTransform.gameObject;
int currentIndex = ObjectsManager.IndexOf(currentObject);
if(currentIndex < 0)
{
Debug.LogErrorFormat(this, "Object {0} is not in list!", currentObject.name);
return;
}
if(currentIndex == 0)
{
// nothing to do go back to
// Except you want wrap around then simply remove this check
Debug.Log("Already is first object in list", this);
return;
}
GameObject newObject = ObjectsManager.GetByIndex(currentIndex - 1);
Transform childOfNewObject = newObject.GetChild(0).GetChild(1);
// Set Camera
// Using simply SetParent with parameter worldPositionStays=false
// reduces it to one single call
camera.transform.SetParent( childOfNewObject, false);
}
And accordingly
void ButtonAction_RightPlusOne()
{
GameObject currentObject = manager.currentObjectTransform.gameObject;
int currentIndex = ObjectsManager.IndexOf(currentObject);
if(currentIndex < 0)
{
Debug.LogErrorFormat(this, "Object {0} is not in list!", currentObject.name);
return;
}
if(currentIndex == ObjectsManager.Count - 1)
{
// nothing to do go forward to
// Except you want wrap around then simply remove this check
Debug.Log("Already is last object in list", this);
return;
}
GameObject newObject = ObjectsManager.GetByIndex(currentIndex + 1);
Transform childOfNewObject = newObject.GetChild(0).GetChild(1);
// Set Camera
// Using simply SetParent with parameter worldPositionStays=false
// reduces it to one single call
camera.transform.SetParent( childOfNewObject, false);
}

dropdown error on device in codenameone

I am implementing drop-drown feature in my app. Its implemented using container with list of elements in it.
Suppose the drop down list has following items aa1, aa2, aa3, aa4 aa5 and so on. And if i search as 'aa' it displays items starting from 'aa', if I select aa5 from list, it takes aa1 and displays that. But whereas if I scroll the items and select its working fine. This problem occurring only on iOS device working perfectly fine on simulator.
the first picture depicts how drop down looks like, in second picture if I search 'ee', it gives list of items starting with 'ee'. If I select 'ee5', it sets to ee1 as shown in picture 3. Problem only on device. Any workaround for this?
So, please let me know whats the issue with this.
Thanks
[![enter image description here][1]][1]
private CustomList itemList;
class CustomList extends List {
int startYPos = -1;
long lastDiff = 0;
Timer t = null;
int draggingState = 0;
public CustomList() {
this.setTensileDragEnabled(false);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(final ActionEvent evt) {
final Runnable rn = new Runnable() {
public void run() {
// Create and show a dialog to allow users to make a selection.
final UiBuilder uib = dm.UiBuilder();
dialog = (Dialog) uib.createContainer(DESIGNER_NAME_DIALOG_COMBOBOX_CONTAINER);
GenericSpinner itemSpinner = (GenericSpinner) uib.findByName(DESIGNER_NAME_DIALOG_COMBOBOX_GENERIC_SPINNER, dialog);
itemSpinner.setPreferredW(Display.getInstance().getDisplayWidth() * 4 / 5);
//remove from parent and replace with a linear list
Container parent = itemSpinner.getParent();
parent.removeComponent(itemSpinner);
// Add the searchable text field box
final TextField tf = (TextField)uib.findByName("Search", dialog);
tf.addDataChangedListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
Object[] items = model.getFilteredItems(tf.getText());
itemList.setModel(new DefaultListModel(items));
}
});
itemList = new CustomList();
itemList.getAllStyles().setBgTransparency(0);
itemList.setItemGap(0);
parent.addComponent(BorderLayout.CENTER, itemList);
final String[] items = model.getItems();
itemList.setModel(new DefaultListModel(items));
itemList.getStyle().setMargin(10, 10, 10, 10);
itemList.setFireOnClick(true);
itemList.setLongPointerPressActionEnabled(false);
ActionListener list = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (model.isUserEditable() && model.getItemCount() > 0) {
int i = itemList.getSelectedIndex();
if (i > items.length - 1) {
return;
}
itemList.getModel().setSelectedIndex(i);
model.onUserDataEntered((String) itemList.getModel().getItemAt(i));
String textToDisplay = (String) itemList.getModel().getItemAt(i);
button.setText(textToDisplay);
}
dialog.dispose();
}
};
itemList.addActionListener(list);
CommonTransitions tran = CommonTransitions.createEmpty();
dialog.setTransitionInAnimator(tran);
dialog.setTransitionOutAnimator(tran);
itemList.setRenderer(new ListRenderer());
//related to dialog to show list of items
//how much space do we really need???
if (cellHeight == 0) {
int dip = Display.getInstance().convertToPixels(1);
int siz = 2;
if (Display.getInstance().isTablet()) {
siz = 4;
}
siz *= 2;
cellHeight = siz * dip;
}
int heightRequired = cellHeight * (items.length + 8);
//is this too much for the screen - we will use 3/4 of the screen height max
int availableHeight = Display.getInstance().getDisplayHeight() * 3;
availableHeight /= 4;
if (heightRequired > availableHeight) {
int topPos = Display.getInstance().getDisplayHeight() / 8;
int bottomPos = topPos + availableHeight;
dialog.show(topPos, topPos, 40, 40);
}
else {
int topPos = (Display.getInstance().getDisplayHeight() - heightRequired) / 2;
int bottomPos = topPos + heightRequired;
dialog.show(topPos, topPos, 40, 40);
}
}
};
}
}
//new code using Multibutton implementation
final String[] listItems = model.getItems();
Display.getInstance().callSerially(() ->{
multiButton= new MultiButton();
multiButton.setTextLine1(s);
dialog.add(multiButton);
multiButton.addActionListener(e -> Log.p("you picked " + multiButton.getSelectCommandText(), Log.ERROR));
}
dialog.revalidate();
});
I would recommend using a Container and simple layout search as demonstrated by code such as this. The code below was taken from the Toolbar javadoc:
Image duke = null;
try {
duke = Image.createImage("/duke.png");
} catch(IOException err) {
Log.e(err);
}
int fiveMM = Display.getInstance().convertToPixels(5);
final Image finalDuke = duke.scaledWidth(fiveMM);
Toolbar.setGlobalToolbar(true);
Form hi = new Form("Search", BoxLayout.y());
hi.add(new InfiniteProgress());
Display.getInstance().scheduleBackgroundTask(()-> {
// this will take a while...
Contact[] cnts = Display.getInstance().getAllContacts(true, true, true, true, false, false);
Display.getInstance().callSerially(() -> {
hi.removeAll();
for(Contact c : cnts) {
MultiButton m = new MultiButton();
m.setTextLine1(c.getDisplayName());
m.setTextLine2(c.getPrimaryPhoneNumber());
Image pic = c.getPhoto();
if(pic != null) {
m.setIcon(fill(pic, finalDuke.getWidth(), finalDuke.getHeight()));
} else {
m.setIcon(finalDuke);
}
hi.add(m);
}
hi.revalidate();
});
});
hi.getToolbar().addSearchCommand(e -> {
String text = (String)e.getSource();
if(text == null || text.length() == 0) {
// clear search
for(Component cmp : hi.getContentPane()) {
cmp.setHidden(false);
cmp.setVisible(true);
}
hi.getContentPane().animateLayout(150);
} else {
text = text.toLowerCase();
for(Component cmp : hi.getContentPane()) {
MultiButton mb = (MultiButton)cmp;
String line1 = mb.getTextLine1();
String line2 = mb.getTextLine2();
boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
line2 != null && line2.toLowerCase().indexOf(text) > -1;
mb.setHidden(!show);
mb.setVisible(show);
}
hi.getContentPane().animateLayout(150);
}
}, 4);
hi.show();

Error in convert inventory from JS to C# - Unity

Hello :) I'm converting now Inventory system but i'm stuck on List / Arrays (JS).
Here's my script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu ("Inventory/Character Sheet")]
[RequireComponent(typeof (Inventory))]
public class Character : MonoBehaviour {
//The Character window (CSheet).
public Transform WeaponSlot; //This is where the Weapons are going to go (be parented too). In my case it's the "Melee" gameobject.
//private Item[] ArmorSlot;
private List<Item> ArmorSlot; //This is the built in Array that stores the Items equipped. You can change this to static if you want to access it from another script.
//public string[] ArmorSlotName;
public List<string> ArmorSlotName; //This determines how many slots the character has (Head, Legs, Weapon and so on) and the text on each slot.
//public Rect[] buttonPositions;
public List<Rect> buttonPositions; //This list will contain where all buttons, equipped or not will be and SHOULD HAVE THE SAME NUMBER OF cells as the ArmorSlot array.
Vector2 windowSize = new Vector2(375,300); //The size of the character window.
public bool useCustomPosition = false; //Do we want to use the customPosition variable to define where on the screen the Character window will appear.
Vector2 customPosition = new Vector2 (70, 70); //The custom position of the Character window.
public GUISkin cSheetSkin; //This is where you can add a custom GUI skin or use the one included (CSheetSkin) under the Resources folder.
public bool canBeDragged = true; //Can the Character window be dragged?
public KeyCode onOffButton = KeyCode.I; //The key to toggle the Character window on and of.
bool DebugMode = false; //If this is enabled, debug.logs will print out information when something happens (equipping items etc.).
static bool csheet = false; //Helps with turning the CharacterSheet on and off.
private Rect windowRect = new Rect(100,100,200,300); //Keeping track of our character window.
//These are keeping track of components such as equipmentEffects and Audio.
private Inventory playersinv; //Refers to the Inventory script.
private bool equipmentEffectIs = false;
private InvAudio invAudio;
private bool invDispKeyIsSame = false;
//Assign the differnet components to variables and other "behind the scenes" stuff.
void Awake ()
{
playersinv = GetComponent<Inventory>();
if (useCustomPosition == false)
{
windowRect = new Rect(Screen.width-windowSize.x-70,Screen.height-windowSize.y-(162.5f+70*2),windowSize.x,windowSize.y);
}
else
{
windowRect = new Rect(customPosition.x,customPosition.y,windowSize.x,windowSize.y);
}
invAudio = GetComponent<InvAudio>();
if (GetComponent<InventoryDisplay>().onOffButton == onOffButton)
{
invDispKeyIsSame = true;
}
}
//Take care of the array lengths.
void Start ()
{
ArmorSlot = new Item[ArmorSlotName.Count];
if (buttonPositions.Count != ArmorSlotName.Count)
{
Debug.LogError("The variables on the Character script attached to " + transform.name + " are not set up correctly. There needs to be an equal amount of slots on 'ArmorSlotName' and 'buttonPositions'.");
}
}
//Checking if we already have somthing equipped
bool CheckSlot(int tocheck)
{
bool toreturn = false;
if(ArmorSlot[tocheck]!=null){
toreturn=true;
}
return toreturn;
}
//Using the item. If we assign a slot, we already know where to equip it.
public void UseItem(Item i, int slot, bool autoequip)
{
if(i.isEquipment){
//This is in case we dbl click the item, it will auto equip it. REMEMBER TO MAKE THE ITEM TYPE AND THE SLOT YOU WANT IT TO BE EQUIPPED TO HAVE THE SAME NAME.
if(autoequip)
{
int index = 0; //Keeping track of where we are in the list.
int equipto = 0; //Keeping track of where we want to be.
foreach(string a in ArmorSlotName) //Loop through all the named slots on the armorslots list
{
if(a == i.itemType) //if the name is the same as the armor type.
{
equipto=index; //We aim for that slot.
}
index++; //We move on to the next slot.
}
EquipItem(i,equipto);
}
else //If we dont auto equip it then it means we must of tried to equip it to a slot so we make sure the item can be equipped to that slot.
{
if(i.itemType==ArmorSlotName[slot]) //If types match.
{
EquipItem(i,slot); //Equip the item to the slot.
}
}
}
if (DebugMode)
{
Debug.Log(i.name + " has been used");
}
}
//Equip an item to a slot.
void EquipItem(Item i, int slot)
{
if(i.itemType == ArmorSlotName[slot]) //If the item can be equipped there:
{
if(CheckSlot(slot)) //If theres an item equipped to that slot we unequip it first:
{
UnequipItem(ArmorSlot[slot]);
ArmorSlot[slot]=null;
}
ArmorSlot[slot]=i; //When we find the slot we set it to the item.
gameObject.SendMessage ("PlayEquipSound", SendMessageOptions.DontRequireReceiver); //Play sound
//We tell the Item to handle EquipmentEffects (if any).
if (i.GetComponent<EquipmentEffect>() != null)
{
equipmentEffectIs = true;
i.GetComponent<EquipmentEffect>().EquipmentEffectToggle(equipmentEffectIs);
}
//If the item is also a weapon we call the PlaceWeapon function.
if (i.isAlsoWeapon == true)
{
if (i.equippedWeaponVersion != null)
{
PlaceWeapon(i);
}
else
{
Debug.LogError("Remember to assign the equip weapon variable!");
}
}
if (DebugMode)
{
Debug.Log(i.name + " has been equipped");
}
playersinv.RemoveItem(i.transform); //We remove the item from the inventory
}
}
//Unequip an item.
void UnequipItem(Item i)
{
gameObject.SendMessage ("PlayPickUpSound", SendMessageOptions.DontRequireReceiver); //Play sound
//We tell the Item to disable EquipmentEffects (if any).
if (i.equipmentEffect != null)
{
equipmentEffectIs = false;
i.GetComponent<EquipmentEffect>().EquipmentEffectToggle(equipmentEffectIs);
}
//If it's a weapon we call the RemoveWeapon function.
if (i.itemType == "Weapon")
{
RemoveWeapon(i);
}
if (DebugMode)
{
Debug.Log(i.name + " has been unequipped");
}
playersinv.AddItem(i.transform);
}
//Places the weapon in the hand of the Player.
void PlaceWeapon (Item item)
{
GameObject Clone = GameObject.Instantiate(item.equippedWeaponVersion, WeaponSlot.position, WeaponSlot.rotation) as GameObject;
Clone.name = item.equippedWeaponVersion.name;
Clone.transform.parent = WeaponSlot;
if (DebugMode)
{
Debug.Log(item.name + " has been placed as weapon");
}
}
//Removes the weapon from the hand of the Player.
void RemoveWeapon (Item item)
{ if (item.equippedWeaponVersion != null)
{
Destroy(WeaponSlot.FindChild("" + item.equippedWeaponVersion.name).gameObject);
if (DebugMode)
{
Debug.Log(item.name + " has been removed as weapon");
}
}
}
void Update ()
{
//This will turn the character sheet on and off.
if (Input.GetKeyDown(onOffButton))
{
if (csheet)
{
csheet = false;
if (invDispKeyIsSame != true)
{
gameObject.SendMessage ("ChangedState", false, SendMessageOptions.DontRequireReceiver); //Play sound
gameObject.SendMessage("PauseGame", false, SendMessageOptions.DontRequireReceiver); //StopPauseGame/EnableMouse/ShowMouse
}
}
else
{
csheet = true;
if (invDispKeyIsSame != true)
{
gameObject.SendMessage ("ChangedState", true, SendMessageOptions.DontRequireReceiver); //Play sound
gameObject.SendMessage("PauseGame", true, SendMessageOptions.DontRequireReceiver); //PauseGame/DisableMouse/HideMouse
}
}
}
}
//Draw the Character Window
void OnGUI()
{
GUI.skin = cSheetSkin; //Use the cSheetSkin variable.
if(csheet) //If the csheet is opened up.
{
//Make a window that shows what's in the csheet called "Character" and update the position and size variables from the window variables.
windowRect = GUI.Window (1, windowRect, DisplayCSheetWindow, "Character");
}
}
//This will display the character sheet and handle the buttons.
void DisplayCSheetWindow(int windowID)
{
if (canBeDragged == true)
{
GUI.DragWindow (new Rect (0,0, 10000, 30)); //The window is dragable.
}
int index = 0;
foreach(Item a in ArmorSlot) //Loop through the ArmorSlot array.
{
if(a == null)
{
if(GUI.Button(buttonPositions[index], ArmorSlotName[index])) //If we click this button (that has no item equipped):
{
InventoryDisplay id = GetComponent<InventoryDisplay>();
if(id.itemBeingDragged != null) //If we are dragging an item:
{
EquipItem(id.itemBeingDragged,index); //Equip the Item.
id.ClearDraggedItem();//Stop dragging the item.
}
}
}
else
{
if(GUI.Button(buttonPositions[index],ArmorSlot[index].itemIcon)) //If we click this button (that has an item equipped):
{
InventoryDisplay id2 = GetComponent<InventoryDisplay>();
if(id2.itemBeingDragged != null) //If we are dragging an item:
{
EquipItem(id2.itemBeingDragged,index); //Equip the Item.
id2.ClearDraggedItem(); //Stop dragging the item.
}
else if (playersinv.Contents.Count < playersinv.MaxContent) //If there is room in the inventory:
{
UnequipItem(ArmorSlot[index]); //Unequip the Item.
ArmorSlot[index] = null; //Clear the slot.
id2.ClearDraggedItem(); //Stop dragging the Item.
}
else if (DebugMode)
{
Debug.Log("Could not unequip " + ArmorSlot[index].name + " since the inventory is full");
}
}
}
index++;
}
}
}
And I have this error:
Assets/Inventory/Scripts/Character.cs(62,17): error CS0029: Cannot implicitly convert type Item[]' toSystem.Collections.Generic.List'
this lane:
ArmorSlot = new Item[ArmorSlotName.Count];
in JS version there were arrays but in c# i convert it to Lists and i have couple of errors ;D Can someone help me with this ? ;/
Error happens over here.
ArmorSlot = new Item[ArmorSlotName.Count];
What is ArmorSlot?
Private List<Item> ArmorSlot; //This is the built in Array that stores the Items equipped. You can change this to static if you want to access it from another script.
you don't make List like normal array.
You don't want List you want Item array.
Fix is like this
private Item[] ArmorSlot;
But maybe you want List because list is easier to control then a native C# array if you wan't to use List you must do something like this
ArmorSlot = new ArrayList<Item>(ArmorSlotName.Count);
But maybe you don't need to put in ArmorSlotName.Count because List is the size of how much items you put inside it.. it gives default size and keeps increasing.
So it's better to just do this
ArmorSlot = new ArrayList<Item>();

Searching Arrays in Java: equals( ) Versus ==

I have an array with 5 elements. If a user inputs a name or a title, it should output that person's or job title's corresponding job title and person. Here's what I got, I'm not sure what I could be doing wrong. Since it's an applet, I don't need a main method right? Did I get stuff mixed up? What could I be doing wrong? Even if I input data that is stored in the array, it always gives me "input did not match any records" I would appreciate any help. Thanks in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment extends JApplet implements ActionListener
{
String[] empName = {"John Jacobs" , "Will Watts","Kevin Krust", "Allan Ayers", "Sam Smith"};
String[] empTitle = {"Software Engineer" , "Database Administrator", "Network Administrator" , "Head Programmer" ,"Department Manager"};
final int ARRAY_SIZE = 5;
boolean validName = false;
boolean validTitle = false;
String nameOfEmployee;
String titleOfEmployee;
JLabel enterInfo = new JLabel("Enter an Employee Name or Job Title");
JTextField userInput = new JTextField(20);
JButton empButton = new JButton ("Press if you entered a name");
JButton titleButton = new JButton ("Press if you entered a title");
JLabel inputDisplay = new JLabel("");
Container con = getContentPane();
public void init()
{
con.add(enterInfo);
con.add(userInput);
con.add(empButton);
con.add(titleButton);
con.setLayout(new FlowLayout());
userInput.addActionListener(this);
empButton.addActionListener(this);
titleButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if (source == empButton)
{
String nameEmp = userInput.getText();
con.remove(enterInfo);
con.remove(userInput);
con.remove(empButton);
con.remove(titleButton);
for (int x = 0; x < ARRAY_SIZE; ++x)
{
if (nameEmp == empName[x])
{
validName = true;
titleOfEmployee = empTitle[x];
}
}
if(validName)
inputDisplay.setText(nameEmp + "is a" + titleOfEmployee);
else
inputDisplay.setText("The title you input did not match any records.");
con.add(inputDisplay);
con.setBackground(Color.YELLOW);
}
else
{
String nameJob = userInput.getText();
con.remove(enterInfo);
con.remove(userInput);
con.remove(empButton);
con.remove(titleButton);
for (int x = 0; x < ARRAY_SIZE; ++x)
{
if (nameJob == empTitle[x])
{
validTitle = true;
nameOfEmployee = empName[x];
}
}
if(validName)
inputDisplay.setText(nameOfEmployee + "is a" + nameJob);
else
inputDisplay.setText("The name you input did not match any records.");
con.add(inputDisplay);
con.setBackground(Color.YELLOW);
}
con.invalidate();
con.validate();
}
}
This
nameEmp == empName[x]
compares object references. What you want is comparison of contents, so you should check
nameEmp.equals(empName[x])
When comparing the value input by the user to the values in your arrays, you need to use the equals function and not ==.
Read why here.

Resources