1、演示视频
Demo – ATEST – PC, Mac & Linux Standalone – Unity 2019.3.6f1 Personal _DX11_ 2022-06-21 14-22-22
2、需要的东西
3、上代码
1)放在任意物体上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetSon : MonoBehaviour
{
public GameObject dad;//父物体的预制体
private Transform[] son;//移动路径
int index;//点位数量
int f=1;//路径索引
public Transform start_;//物体初始位置
public float des;//点位距离物体的距离
public GameObject obj;//需要实例化的点位
Quaternion b = new Quaternion(0, 0, 0, 0);
private GameObject Dad;//父物体
// Start is called before the first frame update
void Start()
{
Dad = Instantiate(Resources.Load(“prefab/GameObject(Clone)”)) as GameObject;
Destroy(Dad.GetComponent<SavePrefab>());
}
// Update is called once per frame
void Update()
{
if (Dad!=null)
{
if (index > 0)//移动
{
des = Vector3.Distance(start_.position, son[f].position);
//print(f + “ffffffffffffffff”);
//print(index + “indexindexindex”);
start_.position = Vector3.MoveTowards(start_.position, son[f].position, Time.deltaTime * 5);
if (des < 0.1f && f < index)
{
f++;
}
}
if (Input.GetMouseButtonDown(0))//发射射线实例化移动点位
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //摄像机需要设置MainCamera的Tag这里才能找到
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
GameObject gameObj = hitInfo.collider.gameObject;
Vector3 hitPoint = hitInfo.point;
GameObject objpos = GameObject.Instantiate(obj, hitPoint, b) as GameObject;
objpos.transform.parent = Dad.transform;
}
}
if (Input.GetKeyDown(KeyCode.Space))//获取移动路径个数,刷新index值
{
index = Dad.transform.childCount;
son = Dad.transform.GetComponentsInChildren<Transform>();
//for (int i = 1; i <= index; i++)
//{
// print(son[i]);
//}
}
}
}
public void ClickAdd()
{
Dad = GameObject.Instantiate(dad);
Dad.AddComponent<SavePrefab>();
}
}
2)放在预制体,路径点的父物体上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class SavePrefab : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
SaveMove();
}
}
public void SaveMove()
{
string localPath = “Assets/Resources/prefab/” + this.gameObject.name+”.prefab”;
PrefabUtility.SaveAsPrefabAsset(this.gameObject, localPath);
}
}
4、代码解释
5、整体思路就是先实例化处一个空物体用来存放路径点,然后再通过鼠标点击地面生成路径点,然后再保存这些路径点至文件夹。再然后运行程序的时候先读取文件夹。