how to anchor gui position to canvas using script (C#)?

For example I have this ongui function which is purely in the script and no where else (means not on scene)

void OnGUI ()
	{
		if (showCountdown)
		{    
			GUI.color = Color.red;    
			GUI.Box ( new Rect (Screen.width / 2 - 100, 50, 200, 175), "GET READY");

			// display countdown    
			GUI.color = Color.white;    
			GUI.Box (new Rect (Screen.width / 2 - 90, 75, 180, 140), countdown);
		}   

	}

now I have my UI anchored to canvas so screen resolution is not an issue, however in case of gui on script it’s giving me problems as on my mobile the gui does not appear at the place I set it to on unity. How can I anchor it to the canvas using script so that different screen resolution doesn’t effect it’s position? ’
I used this code

          public RectTransform panelRectTransform;
            panelRectTransform.anchorMin = new Vector2(1, 0);
		panelRectTransform.anchorMax = new Vector2(0, 1);
		panelRectTransform.pivot = new Vector2(0.5f, 0.5f);

but it didn’t work for some reason, any ideas? I have to complete the game by tonight and this is the last issue I’m facing :frowning:

Those GUI. functions are not related to the canvas. In the scene hierarchy, you can make controls that are children of the canvas.

These controls are all from the UnityEngine.UI namespace, and they inherits from: UI.Selectable
and example is https://docs.unity3d.com/ScriptReference/UI.InputField.html
or https://docs.unity3d.com/ScriptReference/UI.Text.html

You can create these gameobjects at runtime, and attach at each a RectTransform, and the UI component. Then use the RectTransform, to get it positioned, and anchored on your canvas.