Home > OS >  Compare a string in if()
Compare a string in if()

Time:05-07

I'm trying to compare a string in an if(string = ""), but it's apparently not the same

the string is "thisColor", it is defined by the content of a file. I tried using Debug.Log(thisColor), the result is "rouge" but it's not recognized in if(thisColor == "rouge"). I also tried switch(thisColor) then case()...

Maybe it's the encoding..?

Here is the code snippet:

        thisColor = "";

        pixelSetup = GameObject.Find("Pixel"   setupPixelNumber.ToString());

        setupPixelNumber  = 1;

        if (File.Exists("C:/PekmiIndustries/MVPlace/Pixel"   pixell   ".txt"))
        {
            thisColor = File.ReadAllText("C:/PekmiIndustries/MVPlace/Pixel"   pixell   ".txt");
        }
        else
        {
            File.Create("C:/PekmiIndustries/MVPlace/Pixel"   pixell   ".txt").Dispose();
        }

        string[] retourSuppr = new string[] { "\n" };
        foreach(var c in retourSuppr)
        {
            thisColor = thisColor.Replace(c, string.Empty);
        }
        pixell = pixelSetup;

        pixell.GetComponent<Renderer>().enabled = true;

        Debug.Log("thisColor = |"   thisColor   "|");


        if (thisColor != "")
        {
            Debug.Log(thisColor);
            if (thisColor == "rouge")
            {
                Debug.Log("done.");
                pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 0, 0, 1);
                thisColor = "";
            }
            else if (thisColor == "orangeF")
            {
                pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 70f / 255f, 0 / 255f, 1);
                thisColor = "";
            }
            else if (thisColor == "orange")
            {
                pixell.GetComponent<Renderer>().material.color = new Color(255f / 255f, 128f / 255f, 0 / 255f, 1);
                thisColor = "";
            }
            
            else
            {
                Debug.Log("Passed");
            }

thanks :)

CodePudding user response:

i am not sure you "thisColor = File.ReadAllText("C:/PekmiIndustries/MVPlace/Pixel" pixell ".txt");" result,but i think the result contains space bar,so you can try this:

thisColor=thisColor.Replace(" ","")

CodePudding user response:

This is because your file is encoded with something different than UTF-8, which is the default reading method used by ReadAllText

As said in this answer you can tell ReadAllText to use unicode instead.

File.ReadAllText("yourTextFile.txt", ,Encoding.Unicode);
  • Related