For loop only showing last element in string array (Xamarin) - forms

Sorry if tgis sounds like a duplicate question, but most responses seem to be for C# Console apps rather than Visual Studio Xamarin mobile apps.
namespace ArrayPractice
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
string[] StringArray = new string[] { "Apple", "Baker", "Caramel", "Danish" };
int deli = StringArray.Length;
for (int i = 0; i < deli; i++)
{
DeliNames.Text = StringArray[i];
//DeliNames is x:Name assigned to XAML Label } } } }
}
}
}
}
Shouldn't the following code return all the elements in the string array on a separate line, not just the last one. The DisplayAlert is giving me an initial value of 3. then decreasing by 1 when I click OK and finally shows the "Danish"

Currently on each iteration you are assigning the array value to your Text property, you could concatenate it with +=, or you could use a StringBuilder or Span, there are multiple ways.:
// Environment.NewLine for newline
DeliNames.Text += StringArray[i] + Environment.NewLine;

Related

How do I increase the array and add a Gameobject to a new field?

I have a certain array that stores chunks of the world, and I need to increase the array through the script and place the chunk in a new field for the chunk. How can this be done?
I wrote this code:
public class WriteInWorld
{
[MenuItem("Assets/Add To World")]
public static void SetAsWmass()
{
GameObject[] selectedWmass = Selection.gameObjects;
Debug.Log(selectedWmass);
for (int i = 0; i < selectedWmass.Length; i++)
{
selectedWmass[i].GetComponent<Wmasss>().Chunk = selectedWmass[i];
Debug.Log(selectedWmass[i]);
}
//world = Find.FindWorldObjectAsBoolArgument(true);
//Debug.Log(world.GetComponent<World>().Chunk.ToList() + ": :" + world);
}
[MenuItem("Assets/Add To World", isValidateFunction:true)]
public static bool SetAsWmassValidator()
{
return Selection.activeObject is Wmasss;
}
}
Usually you have got 2 options:
If you know how many items you will need to store in a container, you can use an array.
If you don't know how many items you will need to store, a List might be what you're looking for.

Unity EditorWindow OnGUI doesn't save data for List<string[]> types

It appears that anything I add to a List<string[]> will get added, but when I save any scripts and Unity does compiles everything, the items in the list disappears.
Here is a simple class I wrote that just displays a window and adds labels according to how many items are in the list:
public class TestEditorWindow : EditorWindow
{
string windowLabel = "Test Window";
[SerializeField] List<string[]> myList = new List<string[]>();
[MenuItem("Tools/My Window")]
static void Init()
{
TestEditorWindow myWindow = (TestEditorWindow)GetWindow(typeof(TestEditorWindow));
myWindow.Show();
}
private void OnGUI()
{
GUILayout.Label(windowLabel, EditorStyles.boldLabel);
EditorGUILayout.Separator();
GUILayout.BeginVertical("box", GUILayout.ExpandWidth(true));
for(int i = 0; i < myList.Count; i++)
{
EditorGUILayout.LabelField("Stupid");
}
if(GUILayout.Button("+", GUILayout.MaxWidth(30)))
{
//myList.Add(new string[2]); //<-- Also tried it this way
myList.Add(new string[] { "" });
}
GUILayout.EndVertical();
}
}
The window shows and every time I hit the button a new label is added to the window, but as soon as Unity compiles anything, the values go away.
If I change the list to List<string> it behaves as intended
I've also tried setting up the list like so and got the same results:
[SerializeField] static List<string[]> myList;
[MenuItem("Tools/My Window")]
static void Init()
{
myList = new List<string[]>();
TestEditorWindow myWindow = (TestEditorWindow)GetWindow(typeof(TestEditorWindow));
myWindow.Show();
}
Am I doing something wrong with how I'm loading the list?
Unity cannot serialize multidimensional collections.
There is a work around though.
Create a new class that contains the string array, and create a list using that type.
[System.Serializable]
public class StringArray
{
public string[] array;
}
and in your window use:
public List<StringArray> myList = new List<StringArray>();

Unity How to combine each object name?

I put several button and i linked onClick() each buttons.
It's okay to print each button name.
But when i click another button, The text didn't combine previous text...
========================================================
public Text showText; //print text
public int count = 0; // count how many times click button
public void ButtonClick_1()
{
Debug.Log("Button Clicked!");
print(gameObject.name);
if (count == 0) { showText.text = gameObject.name; }
else { showText.text += gameObject.name; }
count++;
}
==================================================
First
click button1 => it's okay to print " button1 "
Second
click button1 again => It's okay to print " button1button1"
Third
click button2 => It's not okay to print. print like "button2". I hope it print"button1button1button2"
==========================================================
I want to figure out this.....
I have to put several buttons so use tag is more useful?
I'm not used to use tag. Hope someone help me out.
So as I understood you have this script on multiple buttons.
You have a check on count which initially is 0 for each individual instance.
So instead you could make it static so it is "shared" between all instances or better said makes it a static class member which is not related to any instance.
public Text showText;
public static int count = 0;
public void ButtonClick_1()
{
Debug.Log("Button Clicked!");
print(gameObject.name);
if (count == 0)
{
showText.text = gameObject.name;
}
else
{
showText.text += gameObject.name;
}
count++;
}
So that the text is only overwritten by the very first button click.
Your comment
Actually i print like "000" ,"001",,"012","123".
sounds like you actually want to print always the last three buttons.
I would rather use e.g. a static List<string> like
private static List<string> lastThreeButtons = new List<string>();
public void ButtonClick()
{
lastThreeButtons.Add(name);
if(lastThreeButtons.Count == 3)
{
showText.text = lastThreeButtons[0] + lastThreeButtons[1] + lastThreeButtons[3];
lastThreeButtons.Clear();
}
}
This is how I would do it :
Have a singleton class :
public class TextManager : MonoBehaviour
{
public static TextManager Instance;
public UnityEngine.UI.Text myUIText;
private void Awake()
{
Instance = this;
}
public void AddLine(string _line)
{
myUIText.text += $"{_line} \n";
}
}
Put this Component on a GameObject and link the UIText in the inspector
Then on my ButtonScript I would have this :
public void ButtonClick()
{
Debug.Log($"{gameObject.name} Clicked!");
TextManager.Instance.AddLine(gameObject.name);
}

Find all children with different tags -Unity

I'm trying to get a number of all children with a certain tag from the parent object.
For example if a parent object has 20 children and their tags can switch between two tags, I would want to find out how many have either tag.
I want to do it on a mouse click. I've tried using transform.childCount and FindGameObjectsWithTag() however I'm not having any luck.
Any suggestions or pointers?
public static class Extensions {
public static int ChildCountWithTag(this Transform tr, string tag, bool checkInactive = false) {
int count = 0;
Transform [] trs = tr.GetComponentsInChildren<Transform>(checkInactive);
foreach(Transform t in trs) {
if(t.gameObject.CompareTag(tag) == true) { count++; }
}
return count;
}
}
Then you call it as:
void Start() {
int result = this.transform.ChildCountWithTag("Tag");
int resultB = this.transform.ChildCountWithTag("OtherTag", true);
}
The first returns how many active with the given tag "Tag", the second how many children with the tag "OtherTag", including inactive ones.

How to filter bad words of textbox in ASP.NET MVC?

I have a requirement in which i wanna filter the textbox value, that is should remove the bad words entered by the user. Once the user enters the bad words and click on submit button, action is invoked. Somewhere in the model(any place) i should be able to remove the bad words and rebind the filtered value back to the model.
How can i do this?
If you can update the solution to MVC 3 the solution is trivial. Just implement the word check in a controller and then apply the RemoteAttribute on the property that should be validated against bad words. You will get an unobtrusive ajax check and server side check with just one method and one attribute. Example:
public class YourModel
{
[Remote("BadWords", "Validation")]
public string Content { get; set; }
}
public class ValidationController
{
public JsonResult BadWords(string content)
{
var badWords = new[] { "java", "oracle", "webforms" };
if (CheckText(content, badWords))
{
return Json("Sorry, you can't use java, oracle or webforms!", JsonRequestBehavior.AllowGet);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
private bool CheckText(string content, string[] badWords)
{
foreach (var badWord in badWords)
{
var regex = new Regex("(^|[\\?\\.,\\s])" + badWord + "([\\?\\.,\\s]|$)");
if (regex.IsMatch(content)) return true;
}
return false;
}
}