YuminekoGame
6/28/2019 - 9:09 AM

RectTransformToWorldFix

using UnityEngine;
using UnityEngine.UI;
public class UIEffect : MonoBehaviour {
    [SerializeField] private RectTransform targetRect;
    [SerializeField] private ParticleSystem particle;
    [SerializeField] private GameObject obj;
    private Canvas _canvas;
    public Canvas Canvas { get { return this._canvas ? this._canvas : this._canvas = targetRect.GetComponent<Graphic> ().canvas; } }

    // Start is called before the first frame update
    void Start () {
        var camera = (Canvas.renderMode == RenderMode.ScreenSpaceOverlay) ? null : Canvas.worldCamera;
        //RectTransformをスクリーン座標に変換
        Vector2 screenPos = RectTransformUtility.WorldToScreenPoint (camera, targetRect.position);

        //ワールド座標
        Vector3 worldPos = Vector3.zero;

        //スクリーン座標→ワールド座標に変換
        RectTransformUtility.ScreenPointToWorldPointInRectangle (targetRect, screenPos, camera, out worldPos);

        //  正しく見えるよう補正
        worldPos += (camera.transform.position - worldPos) * 0.9f;
        particle.transform.position = worldPos;

        particle.Emit (1);
        obj.transform.position = worldPos;
    }

    // Update is called once per frame
    void Update () {

    }
}