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>();
Related
I'm trying to achieve a method that I can call to create multiple items
This is the method I'm trying to get it to work
public void AddMultipleItems(string[] itemKey, int[] amount)
{
for (int i = 0; i < itemKey.Length; i++)
{
Item item;
item = ItemCollection[itemKey[i]];
for (int x = 0; x < amount.Length; x++)
{
if (inventory.CanAddItem(item, amount[x]) == true)
{
inventory.AddItem(item.GetCopy());
}
else if (inventory.CanAddItem(item, amount[x]) == false)
{
Debug.Log("Inventory Full");
break;
}
}
}
}
And then this method will be called to add in items like this:
itemDB.AddMultipleItems(new string[] { "Boots", "Gold Coin", "Apple" }, new int[] {1, 2, 3 });
Result: I get 3 Boots, 3 Gold coin and 3 Apple. when I should be getting 1 Boots, 2 Gold Coin & 3 Apples,
I've done a similar Method like this except it doesn't require array parameters and it works perfectly:
public void AddItems(string itemKey, int amount)
{
//First check if entered itemKey parameter exists in ItemCollection Dictionary
if (ItemCollection.ContainsKey(itemKey))
{
Item item;
item = ItemCollection[itemKey];
if (item != null)
{
//check if we can add the item and the amount of it
if (inventory.CanAddItem(item, amount))
{
//loop through the total amount
for (int i = 0; i < amount; i++)
{
//add the item
inventory.AddItem(item.GetCopy());
}
Debug.Log(itemKey + " Added Successfully!");
}
else
{
Debug.Log("Not enough space in Inventory");
}
}
else
{
Debug.Log("Null Item");
}
}
else
{
Debug.Log(itemKey + " does not exist in ItemDatabase's Dictionary");
}
}
So basically another way of looking at it is how can I turn the AddItems(string itemKey, int amount) into AddItems(string[] itemKey, int[] amount). its the for loop, foreach loop and arrays that are kinda tripping me over since I'm not very good at those.
Appreciate any help, Thank you!
For every item you are iterating over the entire amount array which has 3 entries. I would actually expect that for each item you get 1+2+3 = 6 items added.
Wouldn't you rather want to only get the amount to add from the one entry in amount with the same index as the given itemKey: amount[i]
public void AddMultipleItems(string[] itemKey, int[] amount)
{
for (int i = 0; i < itemKey.Length; i++)
{
Item item;
item = ItemCollection[itemKey[i]];
if (inventory.CanAddItem(item, amount[i]))
{
inventory.AddItem(item.GetCopy());
}
else // your if condition here was redundant
{
Debug.Log("Inventory Full");
}
}
}
In general you already have a method for adding a single item so I wouldn't re-implement that for multiple ones but rather call it from the loop like
public void AddMultipleItems(string[] itemKey, int[] amount)
{
for (int i = 0; i < itemKey.Length; i++)
{
// Instead of re-implement rather call your existing method
// and treat each value pair as if ti was a single add call
AddItems(itemKey[i], amount[i]);
}
}
Then passing in two separate arrays is pretty error prone and hard to maintain. I would probably rather pass in a Dictionary<string, int> like e.g.
public void AddMultipleItems(Dictionary<string, int> itemsToAdd)
{
foreach (var kvp in itemsToAdd)
{
AddItems(kvp.Key, kvp.Value);
}
}
and then call it like
itemDB.AddMultipleItems(new Dictionary<string, int>{ {"Boots", 1}, {"Gold Coin", 2}, {"Apple", 3}});
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);
}
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.
i have one method in class call Class1 like
' public void getEventFromUser() {
int event;
Scanner input = new Scanner(System.in);
date.getDateFromUser();
// od.inputday();
// od.inputyear();
time.getTimeFromUser();
System.out.println("Enter description :");
description = input.nextLine();
}'
and i want to execute this method and store in array in another class
like
public void addEvent() {
if (numEvent == maxEvent) {
System.out.println("error…no more room to add events");
} else {
schedule[numEvent]=getEventFromUser();
int count = 0;
while (count < numEvent - 1) {
if (schedule[numEvent].isEqual(schedule[count])) {
isFound = true;
break;
}
count++;
if (isFound == true) {
System.out.println("Event already exists-notadding");
schedule[numEvent] = null;
} else {
schedule[numEvent].setDate();
schedule[numEvent].setTime();
schedule[numEvent].setDescription();
numEvent++;
//schedule[numEvent]=schedule[numEvent].getEventFromUser();
}
}
}
} '
so,how can i do this?
pls give me some solution
getEventFromUser() doesn't return a value, which is why schedule[numEvent]=schedule[numEvent].getEventFromUser() is giving you trouble.
Without knowing a bit more about what you're trying to do, it's hard to say if you should have getEventFromUser() return a value or have getEventFromUser() directly store a value in a field in the class. (I'm guessing the setDate, setTime and setDescription methods do this.)
I need to be able to draw sequential line segments that have the same Y Coordinate with CPTScatterPlotInterpolationLinear and ones that do not with CPTScatterPlotInterpolationCurved.
As CPTScatterPlotInterpolationCurved draws all lines curved. I am currently doing this by adding multiple plots.
public List<CorrectedGraphPoints> GetCorrectDataPoints(List<PointF> dataSource)
{
int lastIndex = 0;
bool shouldLoop = true;
CPTScatterPlotInterpolation interpolation = CPTScatterPlotInterpolation.Curved;
List<CorrectedGraphPoints> OuterList = new List<CorrectedGraphPoints> ();
if (dataSource [0].Y == dataSource [1].Y)
interpolation = CPTScatterPlotInterpolation.Linear;
while (lastIndex+1 != dataSource.Count) {
OuterList.Add (new CorrectedGraphPoints (interpolation));
while (shouldLoop)
{
OuterList[OuterList.Count -1].Add(dataSource[lastIndex]);
if ((lastIndex + 1) < dataSource.Count) {
if (interpolation == CPTScatterPlotInterpolation.Linear) {
if (dataSource [lastIndex].Y != dataSource [lastIndex + 1].Y) {
interpolation = CPTScatterPlotInterpolation.Curved;
shouldLoop = false;
break;
}
}
if (interpolation == CPTScatterPlotInterpolation.Curved) {
if (dataSource [lastIndex].Y == dataSource [lastIndex + 1].Y) {
interpolation = CPTScatterPlotInterpolation.Linear;
shouldLoop = false;
break;
}
}
}
else {
shouldLoop = false;
break;
}
if (shouldLoop)
lastIndex++;
}
shouldLoop = true;
}
return OuterList;
}
public class CorrectedGraphPoints
{
private List<PointF> points;
public List<PointF> Points { get { return points; } }
private CPTScatterPlotInterpolation interpolation;
public CPTScatterPlotInterpolation Interpolation { get { return interpolation; } }
public CorrectedGraphPoints(CPTScatterPlotInterpolation interpolation)
{
this.interpolation = interpolation;
points = new List<PointF> ();
}
public void Add(PointF point)
{
points.Add (point);
}
}
However creating multiple plots that use fill slows the app down tremendously. I was wondering if I could limit how much I do this? I haven't been able to find a way to change the interpolation for a section?? IS this an just an issue with core plot or is it something wrong with my logic or code?
Another possible solution would be to add additional points to your data to draw the curved sections. This would allow you to use only one plot. The number of additional points needed will depend on several factors including the size of the plot and the line style used to draw the line.