compare string to string array[]
im trying to compare the strings if the strings match i want it make found true this of course will change to making it active user but for now ill settle for just making it true but all my attempts end with only one part of array able to be checked.
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public class CharacterSearcher : MonoBehaviour
{
public GameObject[] Players;
public CharacterData[] playerdata;
public bool search;
public string[] Users;
public string myusername = "Axblade";
public bool found;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
Players = GameObject.FindGameObjectsWithTag("LoggedPlayers");
playerdata = new CharacterData[Players.Length];
Users = new string[Players.Length];
for (int i = 0; i < Players.Length; i++)
{
playerdata[i] = Players[i].GetComponent<CharacterData>();
Users[i] = playerdata[i].username;
}
if (search)
{
foreach (string part in Users)
{
if (string.Equals(part, myusername))
{
found = true;
}
else
{
found = false;
}
}
}
}
}
Answer by Bunny83 · Nov 30, 2017 at 06:20 AM
In general when you search through an array you want something like this:
found = false; // set it to false outside the loop
foreach (string part in Users)
{
if (string.Equals(part, myusername))
{
found = true; // once found set it to true
break; // since we found a match, exit the for loop.
}
}
In your case you set found to true if the name matches and you set it to false when it doesn't match. Since you always iterate through all elements you can only get a "true" when your name is the last element in the array. Because if a different name is at the last element you will set found back to false even it might has been set to true earlier.
Now how can i lets say myplayer gameobject to be the found result?
Answer by NoseKills · Nov 30, 2017 at 06:23 AM
Imagine the Users
list looks like this: ["Axblade", "wrongName"]
Then just walk through your code with this in your mind. You'll notice that found
changes to true
during the first iteration of the loop and back to false
during the second when you compare string.Equals("wrongName", "Axblade")
.
You probably want to exit the loop when you notice the searched name has been found.
found = false;
foreach (string part in Users)
{
if (string.Equals(part, myusername))
{
found = true;
break;
}
}
Also, if this searching is the only thing you use the Users
array for, you should put the part with GameObject.FindGameObjectsWithTag("LoggedPlayers");
call inside the if (search)
because that's a slow thing to do every Update() (and remember to change search
back to false at some point)
only allowed me choose one and you were second sorry but ur both right thankyou