string.EndsWith() always failing ???

Hi Guys,

I have a function that turns off all GameObjects, accepting the one which ends in a particular character. For some reason, even if the character is correct, it still does not leave that particular GameObject on. Here’s the function:

public void UnselectGroup(int _intToStrCheck = 0)
    {
        GameObject[] children = new GameObject[transform.parent.transform.childCount];
        string str = _intToStrCheck.ToString();
        for (int i = 0; i < children.Length; i++ )
        {
            children[i] = transform.parent.transform.GetChild(i).gameObject;
        }

        foreach (GameObject child in children)
        {
            Debug.Log("CHECKING: " + child +"   str: "+ str);
            if (this.gameObject.name.EndsWith(str))
            {
                Debug.Log("CALLED" + this.gameObject.name.EndsWith(str));
                image.sprite = spriteActive;
                // Keep, otherwise...
            }
            else
            {
                Debug.Log("FAILED CALL: " + this.gameObject.name.Contains(str));
                // deactivate!
                child.GetComponent<BtnPressedHandler>().Unselect(true);
            }
        }
    }

No matter wait, it hits ‘FAILED CALL’… and I can’t understand why when I look at the Debug.Log… Here:

CHECKING: Btn_FM1 (UnityEngine.GameObject) str: 3
FAILED CALL: False

CHECKING: Btn_FM2 (UnityEngine.GameObject) str: 3
FAILED CALL: False

CHECKING: Btn_FM3 (UnityEngine.GameObject) str: 3
FAILED CALL: False

You can see that object ‘Btn_FM3’ SHOULD be working. However it still churns out the same result. Without actually being able to return the EndsWith() character (it only returns a bool), I can’t see what it’s checking against exactly… But it LOOKS correct. Right? I’ve tried child.name… It returns the same result!

Can anyone see my flaw?

Thanks!

EDIT: The other posters found the bug, you’re comparing the parent object name instead of the child name.

Are you sure you want to check this.gameObject.name rather than child.gameObject.name?

1 Like

hmm… why you using this.gameObject.name and not child.name for the EndsWith() check?

If this is intentionally, I have another idea what the problem could be:

maybe there is a hidden character in the name of the game object…
Log the following (make sure you have a “using System.Linq;” at the top):

Debug.Log("Last Character: " + this.gameObject.name.Last());

Edit: damn… too slow :frowning:

Well, that was embarrassing lol. Thanks :slight_smile: