Unity随机Prefab,自动前往某点处理

本文章由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 initialization
	void Start () { 
        mbouds = mObjArea.GetComponent<Collider>().bounds;
        InvokeRepeating("NewPrefabInstance", 1, 5);//1秒后调用LaunchProjectile () 函数,之后每5秒调用一次
	}
	
	// Update is called once per frame
	void 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 initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == tagName)
        {
            GameObject.Destroy(other.gameObject);
        }

    }
}


四,说明

这个过程中,要设置目标点为的属性如下:



而prefab对象也需要给它一个rigidbody,否则他们的碰撞不起作用。



基本上做了一个能随机位置产生一个对象,然后对象自动寻找目的,到达目的地的小功能!


---------

若有问题,请随时联系!

非常感谢!!





原文地址:https://www.cnblogs.com/qitian1/p/6461947.html