(1)下準備
- 適当なオブジェクトを1つ作成
- 名前を「RandomEnemy」に変更
(2)スクリプトの作成
- 新規にC#スクリプトの作成
- 名前を「RandomMovement」に変更
- 下記のコードを書いてチェック
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomMovement : MonoBehaviour
{
private float chargeTime = 5.0f;
private float timeCount;
void Update()
{
timeCount += Time.deltaTime;
// 自動前進
transform.position += transform.forward * Time.deltaTime;
// 指定時間の経過(条件)
if(timeCount > chargeTime)
{
// 進路をランダムに変更する
Vector3 course = new Vector3(0, Random.Range(0, 180), 0);
transform.localRotation = Quaternion.Euler(course);
// タイムカウントを0に戻す
timeCount = 0;
}
}
}
(3)設定&再生
- スクリプトをオブジェクトに追加
- ゲームを再生
- 敵が5秒ごとにランダムに方向を変えて動き回れば成功です。

