2
public string OpenDialogueFile(string dialogueName) {
    if(dialogues == null) {
        dialogues = Resources.LoadAll<TextAsset>("Dialogue");
    }
    var text = "";
    foreach(var ta in dialogues) {
        print(ta.name + ".." + dialogueName);
        if(ta.name == dialogueName) {
            print("Found");
            text = ta.text;
            break;
        }
    }
    return text;
}

This code should find a plain text file with the name requested and spit out the contents.

With the files "test1 and test2" in Resources/Dialogue and requesting test1, the output is

test1..test1
Found

When test2 is requested, however

test1..test2
test2..test2

The program claims that test2 is unequal to test2.

Both ta.name and dialogueName are strings, so it should be testing equality by content.

Is there something wrong with my equality operation?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Gigimoi
  • 125
  • 2
  • 11

3 Answers3

3

Try cleaning your strings from whitespaces before comparing them

var cleanDialogueName = dialogueName.Trim();
foreach(var ta in dialogues) 
{
    var cleanName = ta.name.Trim();

    print(cleanName + ".." + cleanDialogueName);
    if (cleanName == cleanDialogueName)
    {
        print("Found");
        text = ta.text;
        break;
    }
 }
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • 2 problems with this. First it should be `char.IsLetterOrDigit(c)` and secondly, it's potentially dangerous as it's stripping ALL whitespace so `"abc def"` is equal to `"a bcdef "` – DavidG May 26 '14 at 22:38
  • Fixed the code. OP needs to tell us if there can be white spaces inside those strings – Yuval Itzchakov May 26 '14 at 22:39
  • 1
    I'm not comfortable with stripping those out, I'd much rather go with trimming from the start/end like this `ta.name.Trim()` – DavidG May 26 '14 at 22:41
  • Modified to use Trim(). Thanks @DavidG – Yuval Itzchakov May 26 '14 at 22:45
  • This resolved it, any ideas on how that whitespace got in there? The file name has no whitespace in it and neither does the request. – Gigimoi May 26 '14 at 23:04
2

You are right, "test2" should equal to "test2". Convert the strings to char arrays with the string.ToCharArray() method to detect the problem. Check the number of characters and their value. Maybe it is an Encoding problem.

user3636971
  • 214
  • 1
  • 5
0

Instead of using the == Operator it is recommended to use the .equals method of the String class to compare Strings for equality.

For more inforation please refer to the msdn documentation or this stackoverflow post

Using .equals instead of == should resolve your problem without having to resort to crazy hackish workarounds

Community
  • 1
  • 1
Vogel612
  • 5,620
  • 5
  • 48
  • 73