ゲームオブジェクトを巡回させる(AI無し)

スクリプトがアサインされたゲームオブジェクトを毎回決まったルートを巡回させます.

下のスクリプトをPatrol.csとして保存しUnityに読み込みます.

using UnityEngine; using System.Collections; public class Patrol : MonoBehaviour { [SerializeField, TooltipAttribute("経由地点の数を入力し,シーン上に配置した空のオブジェクトをアサインします")] public Transform[] wayPoints; public Transform target; public float speed; public int currentRoot; void Update() { //配列に入れたTransformを順に巡る.AIを使っていればスムーズに曲がるがこれは鋭角に曲がる float step = speed * Time.deltaTime; transform.position = Vector3.MoveTowards(transform.position, wayPoints[currentRoot].position, step); Vector3 pos = wayPoints[currentRoot].position; float test = Vector3.Distance(target.position, pos); transform.LookAt(pos); if(Vector3.Distance(transform.position, pos) < 0.5f) { currentRoot = (currentRoot < wayPoints.Length - 1) ? currentRoot + 1 : 0; } } }

シーン内に巡回するGameObjectを配置します.

図ではCubeを選択しています

このGameObjectにPatrol.csをアサインします.

Sizeは巡回箇所の数で,ここに数字を入れると下に入力フィールドが現れます.Speedには適当な数字を入れておきます.

Elementには GameObject>CreateEmptyで作成した空のオブジェクト(位置情報のみ)を配置いれます.

これで再生すると,Patrol.csをアサインしたGameObjectがWayPointsを巡回するようになります.