【unity进阶】运行时实例化预设

作者: 霸俊流年 | 来源:发表于2016-03-02 10:05 被阅读677次

运行时实例化预设

预设是结合gameobject和components并进行重用的一种方式

优点

  • 可以通过一句话实例出一个比较复杂的物体,如果不用预设需要很多行
  • 可以在场景,监视面板迅速更新,测试,修改预制体
  • 可以不修改实例代码而修改预制体本身来修改效果

案例

构建墙

  1. 未使用预设通过代码构建一块砖墙
    public class Instantiation : MonoBehaviour { void Start() { for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.AddComponent<Rigidbody>(); cube.transform.position = new Vector3(x, y, 0); } } }
    没有添加其他组件的情况下就有3行代码来生成。
  2. 使用预设
    public Transform brick;
    void Start() {
    for (int y = 0; y < 5; y++) {
        for (int x = 0; x < 5; x++) {
                Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity);
        }
    }
    }```
    代码很简洁而且重用性很高。
    
    

实例化火箭并且爆炸

1.实例化火箭

// Require the rocket to be a rigidbody.
// This way we the user can not assign a prefab without rigidbody
public Rigidbody rocket;
public float speed = 10f;

void FireRocket () {
Rigidbody rocketClone = (Rigidbody) Instantiate(rocket, transform.position, transform.rotation);
rocketClone.velocity = transform.forward * speed;

// You can also acccess other components / scripts of the clone
rocketClone.GetComponent<MyRocketScript>().DoSomething();
}

// Calls the fire method when holding down ctrl or mouse
void Update () {
if (Input.GetButtonDown("Fire1")) {
FireRocket();
}
}

2.用残骸取代原本物体本身

public GameObject wreck; 
// As an example, we turn the game object into a wreck after 3 seconds automatically
IEnumerator Start() {
yield return new WaitForSeconds(3);
KillSelf();
}

// Calls the fire method when holding down ctrl or mouse
void KillSelf () {
// Instantiate the wreck game object at the same position we are at
GameObject wreckClone = (GameObject) Instantiate(wreck, transform.position, transform.rotation);

// Sometimes we need to carry over some variables from this object
// to the wreck
wreckClone.GetComponent<MyScript>().someVariable = GetComponent<MyScript>().someVariable;

// Kill ourselves
Destroy(gameObject);
}
}

实例化一组特定的物体

1.实例化一个圆圈

// Instantiates a prefab in a circle

public GameObject prefab;
public int numberOfObjects = 20;
public float radius = 5f;

void Start() {
for (int i = 0; i < numberOfObjects; i++) {
float angle = i * Mathf.PI * 2 / numberOfObjects;
Vector3 pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
Instantiate(prefab, pos, Quaternion.identity);
}
}

2.在一个网格实例化预制体

// Instantiates a prefab in a grid

public GameObject prefab;
public float gridX = 5f;
public float gridY = 5f;
public float spacing = 2f;

void Start() {
for (int y = 0; y < gridY; y++) {
for (int x = 0; x < gridX; x++) {
Vector3 pos = new Vector3(x, 0, y) * spacing;
Instantiate(prefab, pos, Quaternion.identity);
}
}
}

相关文章

网友评论

本文标题:【unity进阶】运行时实例化预设

本文链接:https://www.haomeiwen.com/subject/ytdnkttx.html