Home>

I want to display a GameObject on the button when I press it.

I want to display the GameObject in the center of the button, but it is displayed at a position where the x and y axes are slightly offset.
*There is no problem with Z axis as it is (because I want to display the GameObject in front of the button)

button coordinates: (x)-426, (y)−407, (z)0
GameObject coordinates: (x)-1.073298, (y)-0.4712038, (z)10

Applicable source code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StumpGenerator: MonoBehaviour
{
    public GameObject stumpPrefab;
    public Vector3 buttonPos;
    public void Stump()
    {
          buttonPos = this.transform.position;
          buttonPos.z = 10f;
          Instantiate(stumpPrefab, buttonPos,stumpPrefab.transform.rotation);
    }
What I tried

The anchor of the button is the center.

Supplementary information (FW/tool ​​version, etc.)

mac(ver.10.13.2) Unity2019.4.0f1 atom (text editor)

  • Answer # 1

    Buttons are the UI, usually representing screen coordinates. This is two-dimensional. GameObject represents the world coordinate system in the scene. It's 3D, but it's the same in 2D.

    In other words, the UI (screen) and the game usually exist in different spaces, and the UI is overlaid on the screen of the game (taken by the camera). In other words, the coordinate system is different.

    Therefore, Position of Transform and Position of RectTransform cannot be treated in the same way. The coordinates need to be converted.

    There are many ways to do this, which are explained in the next article.

    Conversion between Screen coordinates and World (3D) coordinates

    As for what kind of method should be taken this time, I think that "converting the coordinates of the UI to World Space" is good as far as reading the question.

    The question, though, seems to be a 3D game, but the question is how to determine the depth of the game when there is no depth in the UI. If there are no obstacles that can hit the Ray, you cannot use RectTransformUtility.ScreenPointToRay and you need to use RectTransformUtility.ScreenPointToWorldPointInRectangle.

  • Answer # 2

    When you specify the button instead of GameObject in the select object of On click() item of Button component, GameObject is displayed centering on the coordinates of button.
    It seems that "this" in the script was getting the coordinates of "A GameObject that was properly created for Prefab" instead of "the relevant button".