クリックした場所にオブジェクトを表示するプログラム(グリッドガイド版)。
ChatGPT-4で出力したコードに、少し改変を加えたものです。
グリッドガイド無し版、アイソメトリックグリッドに沿わせる方法はそれぞれ以下:
(グリッドガイド無し版)
tomo-mana.hatenablog.com
(アイソメトリックグリッド版)
tomo-mana.hatenablog.com
コード
AddGameObjectOnClick2.cs
using UnityEngine; using System; // Math // ChatGPT-4 2023/5/8 // 任意の場所にオブジェクトを配置(格子グリッド版) public class AddGameObjectOnClick2 : MonoBehaviour { public GameObject circlePrefab; public Vector2 gridSize; public Vector2 gridOffset; void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 gridPos = GetGridPosition(mousePos); GameObject newCircle = Instantiate(circlePrefab, gridPos, Quaternion.identity); } } Vector3 GetGridPosition(Vector3 mousePos) { float x = (float)Math.Round(mousePos.x / gridSize.x) * gridSize.x + gridOffset.x; float y = (float)Math.Round(mousePos.y / gridSize.y) * gridSize.y + gridOffset.y; return new Vector3(x, y, 0); } }
プレハブ(Prefab)
スプライトで作ったプレハブを用意します。UGUIコンポーネント(Imageなど)では動作しません。
Hierarchyウィンドウで スプライト(ここでは仮に 2D Objects → Sprites→Circle)を作成し、
作成されたゲームオブジェクトをProjectフォルダにドラッグ&ドロップします。
作成したプレハブを、先ほどのコンポーネントにアタッチします。
circlePrefabという名前ですが、任意のスプライトのPrefabで動作します。
動作例
クリックした場所にオブジェクトを表示してくれます。
youtu.be