unity脚本中运行时实例化一个prefab

来源:互联网 发布:如何查询数据库名称 编辑:程序博客网 时间:2024/05/16 18:55

在unity中实例化一个prefab 比实例化一个物体省代码,而且更方便灵活

  • 实例化一个object并创建:
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);            }        }    }
  • 实例化一个prefab,需提前创建好一个cube,加组件Rigidbody,创建prefab,并把该cube拖到prefab上,代码只需要两句:
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);        }    }}
  • 而且修改prefab时,不需要修改代码,灵活性好。

增加大量固定格式的物体,用实例化prefab的方法也更方便

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);    }}