Unity3D中预制体Prefab的应用

来源:互联网 发布:淘宝封号花呗怎么处理 编辑:程序博客网 时间:2024/06/07 07:31

预制体Prefab;相对于一个GameObject模板,方便多次使用。



预制体,如何通过脚本动态加载呢:

using System.Collections;using System.Collections.Generic;using UnityEngine;public class LoadPrefab : MonoBehaviour {    public GameObject bullet;// Use this for initializationvoid Start () {        Instantiate(bullet);}// Update is called once per framevoid Update () {}}

1. 挂载到某个GameObject下面:


using System.Collections;using System.Collections.Generic;using UnityEngine;public class LoadPrefab : MonoBehaviour {    public GameObject goBullet;    private GameObject bullet;// Use this for initializationvoid Start () {        bullet = Instantiate(goBullet);        bullet.transform.parent = this.transform;}// Update is called once per framevoid Update () {}}


2. 将资源放到Resources下

using System.Collections;using System.Collections.Generic;using UnityEngine;public class LoadPrefab : MonoBehaviour {    public GameObject goBullet;    private GameObject bullet;// Use this for initializationvoid Start () {        bullet = Resources.Load("Bullet") as GameObject;        bullet.transform.parent = this.transform;}// Update is called once per framevoid Update () {}}


3.给GameObject挂载脚本
using System.Collections;using System.Collections.Generic;using UnityEngine;public class CreateObject : MonoBehaviour {    GameObject gun;// Use this for initializationvoid Start () {        gun = new GameObject("gun");        gun.AddComponent<LoadPrefab>();}// Update is called once per framevoid Update () {}}
1 0
原创粉丝点击