- Home /
object.ToString never equals the string
I am trying to test an an object's name against a string to determine spawn details and I am failing miserably.
Here is what I am trying:
public GameObject button;
string thisButton;
void Start () {
thisButton = button.ToString() ;
string a = "Button";
}
public void Summon()
if (thisButton.Equals (a))
{
Instantiate (defender , buttonPos.position , Quaternion.Euler(0, -90, 0));
}
}
I have also tried :
if (thisButton == a )
and
if (thisButton == "Button" )
thanks in advance for your answers
Answer by andzq · Oct 14, 2016 at 10:18 PM
That is because the returned string from button.ToString will not only be the name of the object in the hierarchy.
It will most likely be "Button (UnityEngine.GameObject)"
So in order to effectively compare the toString() of the gameobject to your manually set string, you need to trim the returned string first. One possible approach could be:
thisButton = button.ToString();
string a = "Button";
string[] split = thisButton.Split(' ');
print(a.Equals(split[0]).ToString());
This issue was driving me crazy and this solved it, thanks so much! I tried to print the string in the log and it never showed the part after the space, but I guess it was there all the same...
Answer by tanoshimi · Oct 14, 2016 at 09:55 PM
I'm guessing you might be after
if (thisButton.name == "Button")
?