使用了官方文档给的例子,自己试着重新写一遍,学习一遍。以下链接为官网给的例子,也可以去官网相关文档上面下载。
链接:https://pan.baidu.com/s/1xlPmslZFHuvfXZzXb27dqQ
提取码:gjeg
在运行时实例化prefabs一般应用于以下几种情况:
1、使用多个预设体建立一个特定的结构形状。
例如使用立方体的预设体在运行时创建一堵墙。输入墙的高度和宽度。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateWall : MonoBehaviour
{
public GameObject prefab;
public int width=10;//墙面宽度
public int height = 5;//墙面高度
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
Instantiate(prefab, new Vector3(i, j, 0), Quaternion.identity);
}
}
}
}
效果图:
2、实例化子弹类 和爆炸的实现。
此处声明prefab时可以使用Rigidbody,以此来确保拖入的prefab上存在Rigidbody。
public Rigidbody projectile;
public float speed = 4;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Rigidbody p = Instantiate(projectile, transform.position, transform.rotation);
p.velocity = transform.forward * speed;
}
}
3、用布娃娃或者残骸取代角色