How to move empty GameObject to a Canvas?

The main goal is to automatic position the empty gameobject in the center of the canvas.

I have in the Hierarchy empty GameObject at position 0,0,0 and i also have a canvas in the hierarchy also at position 0,0,0 and i want in a script to move the empty GameObject to the canvas.

The canvas Render Mode is set to World Space.

the problem is that the empty GameObject never move to the canvas and if i try to drag and change the empty GameObject position while the game is running the empty gameobject will move and return back to it’s original position. my guess is that because both the canvas and the empty gameobject on position 0,0,0 then the empty gameobject move to his own position 0,0,0

anyway for testing i changed the RectTransform in the script to Transform and assigned the main camera and the empty gameobject is moving to the main camera.

the problem is with the canvas.

here is a screenshot of the canvas and the canvas settings in inspector and the empty gameobject at least in the game view window they seems not to be in same position but they are at 0,0,0

and screenshot of the empty gameobject settings

and this is the script that is attached to the empty gameobject.

using UnityEngine;

public class CenterEmptyGameObject : MonoBehaviour
{
    public RectTransform canvasTransform; // The RectTransform of the Canvas
    public float speed; // Speed of movement

    void Start()
    {
        if (canvasTransform == null)
        {
            Debug.LogError("Canvas Transform is not assigned!");
        }
    }

    private void Update()
    {
        // Move the Empty GameObject towards the Canvas' World Space position
        transform.position = Vector3.MoveTowards(transform.position, canvasTransform.position, speed * Time.deltaTime);
    }
}

Generally any attempt to move GameObjects within a canvas is Really Hard Stuff™.

The best solution is to use the various Layout Components to do what you need.

Here are the official docs on how to make your UI handle various resolutions and aspect ratios cleanly:

Here are some notes on UI Anchoring, Scaling, CanvasScaler, etc:

Usually you need to choose a suitable ScaleMode and MatchMode in the Canvas Scaler and stick with it 100%. Generally if you change those settings you will often need to redo your UI entirely.

Here’s some more fit-inside-UI-content notes:

https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/HOWTO-UIFitContentSize.html

I also use this CanvasScalerOrientationDriver utility to make sharing UI for Landscape / Portrait easier. Read what it does carefully.