標籤:碰撞 隨機地點 銷毀對象 ai
本文章由cartzhang編寫,轉載請註明出處。 所有權利保留。
文章連結: http://blog.csdn.net/cartzhang/article/details/47337029
cartzhang
對與U3D AI,看了下,自己做了小功能,以備後用啊!
一,在某地區隨機產生某個對象
C# 檔案名稱為RadomAPoint.cs
using UnityEngine;using System.Collections;public class RadomAPoint : MonoBehaviour { public GameObject mObjArea; // 隨機地區 public GameObject prefabObj; // 對象prefab public string mytag; // 對象標籤 public string targetTag; // 目標對象標籤 public int ObjectNumber; // 情境中整體prefab 個數。 private Bounds mbouds; private Vector3 tmp;// Use this for initializationvoid Start () { mbouds = mObjArea.GetComponent<Collider>().bounds; InvokeRepeating("NewPrefabInstance", 1, 5);//1秒後調用LaunchProjectile () 函數,之後每5秒調用一次}// Update is called once per framevoid Update () { } void NewPrefabInstance() { GameObject[] root = GameObject.FindGameObjectsWithTag(mytag); if (root.Length <= ObjectNumber) { Vector3 randomPos = RadomVector3(mbouds.min, mbouds.max); //GameObject tmpGameObj = Resources.Load(prefabName) as GameObject; //tmpGameObj.transform.position = randomPos; Quaternion q = Quaternion.identity; GameObject tmpGameObj = GameObject.Instantiate(prefabObj, randomPos, q) as GameObject; tmpGameObj.GetComponent<AIBehaviourScript>().TargetObject = GameObject.FindWithTag(targetTag).transform; } } Vector3 RadomVector3(Vector3 min, Vector3 max) { tmp.x = Random.Range(min.x, max.x); tmp.y= Random.Range(min.y, max.y); return tmp; }}
二、自己做了個prefab,添加了自動找到目標的功能。
特別簡單的代碼:
using UnityEngine;using System.Collections;public class AIBehaviourScript : MonoBehaviour{ public Transform TargetObject = null; void Start() { if (TargetObject != null) { GetComponent<NavMeshAgent>().destination = TargetObject.position; } } void Update() { }}
三,遇到目標後,自動銷毀
代碼:
using UnityEngine;using System.Collections;public class BoxCollisionDestory : MonoBehaviour { public string tagName;// Use this for initializationvoid Start () {}// Update is called once per framevoid Update () {} void OnTriggerEnter(Collider other) { if (other.gameObject.tag == tagName) { GameObject.Destroy(other.gameObject); } }}
四,說明
這個過程中,要設定目標點為的屬性如下:
而prefab對象也需要給它一個rigidbody,否則他們的碰撞不起作用。
基本上做了一個能隨機位置產生一個對象,然後對象自動尋找目的,到達目的地的小功能!
---------
若有問題,請隨時聯絡!
非常感謝!!
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Unity隨機Prefab,自動前往某點處理