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