Unity随机Prefab,自动前往某点处理
2024-08-25 10:07:39
对与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,否则他们的碰撞不起作用。
基本上做了一个能随机位置产生一个对象,然后对象自动寻找目的,到达目的地的小功能!
最新文章
- 《与小卡特一起学Python》 Code6 注释
- 每日英語2013.09.09(Email常用單字)
- MyBatis操作指南-配置结果映射一对一,一对多,多对多(基于注解)
- 无法获得锁 /var/lib/dpkg/lock - open (11: 资源临时不可用)
- 微信 关闭手机微信内置浏览器的js
- 代码片段--Makefile之大型工程项目子目录Makefile的一种通用写法
- js两种创建对象方式
- Cacti以MB为单位监控流量
- BZOJ1677: [Usaco2005 Jan]Sumsets 求和
- c#中使用log4net工具记录日志
- Insecure default in Elasticsearch enables remote code execution
- mybatis简单搭建
- Luogu P5285 [十二省联考2019]骗分过样例
- 针对主机CPU idle性能情况需求脚本编写
- c/c++ 标准库 map multimap元素访问
- python 可调用对象之类实例
- C# Note25: .Net Core
- Android 自定义TextView 实现文本间距
- Python 学习第二章
- nwjs问题总结