Skip to content

Instantly share code, notes, and snippets.

@nomissbowling
Last active July 11, 2018 11:39
Show Gist options
  • Save nomissbowling/4bce7046547a041a1c425911bfc4f38d to your computer and use it in GitHub Desktop.
Save nomissbowling/4bce7046547a041a1c425911bfc4f38d to your computer and use it in GitHub Desktop.
Chaser (NavMeshAgent)
/*
Chaser.cs (like as EnemyMovement.cs)
Hierarchy - Create - 3D Object - Cylinder (あるいは prefab import) - Enemy
Hierarchy - Enemy - Inspector - Add Component - Navigation - Nav Mesh Agent
Project - Create - C# Script - Chaser (Chaser.cs 内容はコピペ等)
Chaser - Enemy の上にドラッグドロップ (Inspector 上では Nav Mesh Agent の後)
Hierarchy - Create - 3D Object - Terrain (あるいは 地形データ import)
Menu - Window - Navigation (Inspector の横に出来る)
地形データ - Navigation - Bake - (位置等 パラメータ 調整) - Bake ボタン押す
Enemy - Navigation - Bake - (位置等 パラメータ 調整) - Bake ボタン押す
Menu - Window - Console (出てないときは出しておく)
実行 正常なら追跡
(上の手順が足りないと no valid NavMesh とか SetDestination とかでエラー)
地形データで Bake してないとき
場所: nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
内容: Failed to create agent because there is no valid NavMesh
場所: nav.SetDestination(player.position);
内容: "SetDestination" can only be called on an active agent
that has been placed on a NavMesh.
Enemy の Inspector で Add Component してないとき
場所: UnityEngine.AI.NavMeshAgent.SetDestination ...
内容: MissingComponentException:
There is no 'NavMeshAgent' attached to the "Enemy" game object,
but a script is trying to access it.
You probably need to add a NavMeshAgent to the game object "Enemy".
Or your script needs to check if the component is attached
before using it.
まだ判ってないこと
階段を登ると追いかけて来ない?(Y方向?)
壁の陰に入ると回り込まずに引っかかる?
常に背後にまわる方法?
*/
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System; // Math
public class Chaser : MonoBehaviour {
int cnt = 0;
public float dT = 0.00001f;
public Transform player, enemy;
//PlayerHealth playerHealth;
//EnemyHealth enemyHealth;
UnityEngine.AI.NavMeshAgent nav;
void Awake(){
// player = GameObject.FindGameObjectWithTag("Unitychan").transform;
player = GameObject.Find("Unitychan").transform;
enemy = GameObject.Find("Enemy").transform;
//playerHealth = player.GetComponent<PlayerHealth>();
//enemyHealth = enemy.GetComponent<EnemyHealth>();
nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
}
void OnDestroy(){
Debug.Log("Chaser: Destroy");
}
void Start(){
Debug.Log("Chaser: Start");
}
void Update(){
++cnt;
if(cnt % 60 == 0) Debug.Log("Chaser: " + cnt);
Vector3 unitypos = player.position;
Vector3 enemypos = enemy.position;
Debug.Log("unitypos: " + unitypos.x + ", " + unitypos.z);
Debug.Log("enemypos: " + enemypos.x + ", " + enemypos.z);
//if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0){
nav.SetDestination(player.position);
//}else{
// nav.enabled = false;
//}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment