拡張メソッドサンプル
ゲームオブジェクトの移動を制限するサンプルです。
拡張メソッドを使っています。
- Projectウィンドウに保管したまま
using UnityEngine; public static class ExtensionTest { public static void ClanpTransform(this Transform tran, Vector3 move, Vector3 min, Vector3 max) { var pos = tran.position + move; pos.x = Mathf.Clamp(pos.x, min.x, max.x); pos.y = Mathf.Clamp(pos.y, min.y, max.y); pos.z = Mathf.Clamp(pos.z, min.z, max.z); tran.position = pos; } }
- Sphereオブジェクトにアタッチ
using UnityEngine; public class PlayerController : MonoBehaviour { [Header("移動制限")] [SerializeField] Vector3 min = new Vector3(-10, 0, -10); [SerializeField] Vector3 max = new Vector3(10, 0, 10); [SerializeField, Header("移動速度")] float speed = 10; void Update() { var moveX = Input.GetAxis("Horizontal"); var moveZ = Input.GetAxis("Vertical"); var move = new Vector3(moveX, 0, moveZ); transform.ClanpTransform(move * speed, min, max); } }