Unity2D:プレハブをマウス位置に生成するスクリプト

Unity

CreateBlock

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreateBlock : MonoBehaviour
{
    public GameObject block;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
		if (Input.GetMouseButtonDown(0))
		{
            // スクリーン上のマウス座標を取得
			Vector3 position = Input.mousePosition;
            position.z = 10f;   // z軸修正(z=0だとうまくワールド座標に変換されないため)

            // スクリーン座標をワールド座標(シーン上の座標)に変換
            Vector3 worldPosition = Camera.main.ScreenToWorldPoint(position);

            // ブロックを生成
			Instantiate(block, worldPosition, Quaternion.identity);
		}    
    }
}

コメント