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

I’m guessing you might be after

if (thisButton.name == "Button")

?

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());