GUI.Button not showing up

OK, I know I’m doing something wrong here. I’m trying to make a GUI.Button in a new scene I’m writing with this code:

	void Start () {
		// Define temporary variables
		float startButtonTop;
		float startButtonLeft;

		// Determine where the start button will be
		startButtonTop = transform.position.y - titleHeight - 50f;
		startButtonLeft = transform.position.x + (titleWidth / 4f);
		startButtonWindow = new Rect(startButtonLeft, startButtonTop, (titleWidth / 2f), 50f);
	}

	void OnGUI () {
		if(GUI.Button(startButtonWindow, "START"))
		{
			Debug.Log("Button pressed");
		}
	}

The script is attached to a SpriteRenderer. The titleHeight and titleWidth variables are floats, and the Debug.Log is a placeholder. What’s happening is nothing; the GUI.Button won’t show up. This is extremely confusing for me, as similar code attached to a SpriteRenderer in a different scene works fine. Does anyone know what I’m doing wrong?

The problem is that transform.position gives you a world point and GUI uses screen point.
so I’m guessing you get negative values on startButtonTop that causes the button to be out of screen.
anyway, to fix this, use this instead:

void Start () {
       // Define temporary variables
       float startButtonTop;
       float startButtonLeft;
 
       // Determine where the start button will be
       Vector3 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
       startButtonTop = screenPosition.y - titleHeight - 50f;
       startButtonLeft = screenPosition.x + (titleWidth / 4f);
       startButtonWindow = new Rect(startButtonLeft, startButtonTop, (titleWidth / 2f), 50f);
    }
 
    void OnGUI () {
       if(GUI.Button(startButtonWindow, "START"))
       {
         Debug.Log("Button pressed");
       }
    }

notice that if you use a different camera you need to change the Camera.main to your current camera.

if you want to know more about screenPoint,worldPoint etc… go to: