您的位置:首页 > 移动开发 > Unity3D

unity开发 --------- prefab

2014-03-19 09:48 183 查看
当我们在EditMode下需要用脚本批量添加prefab时,可以用
PrefabUtility.InstantiatePrefab(prefab) as GameObject;


注意:如果用GameObject.Instantiate来创建,创建的不是prefab。也就是说当我们在Assets中修改prefab时,Scene中的prefab并不会做相应的修改。

下面是一个在EditMode下自动生成prefab并自动排序的脚本

using UnityEngine;
using UnityEditor;
using System.Collections;

[ExecuteInEditMode]
public class shuzu : MonoBehaviour {

public GameObject prefab;

public int weidu = 10;

public bool reset = false;

public bool sort = false;

// 由于unity中的二维数组无法在Inspector中显示,所以用下面的形式代替二维数组
[System.Serializable]
public class test
{
public gridId[] testids;
}
public test[] ids;

void Update()
{
if (reset) {
resetnow();
reset = false;
}

if (sort) {
sortnow ();
sort = false;
}

}

// 生成prefab,并作为该object的子object。
// 同时关联到二维数组中(此步骤是为了排序用)
void resetnow()
{
while (transform.childCount > 0)
DestroyImmediate (transform.GetChild (0).gameObject);
foreach (test t in ids) {
t.testids = new gridId[weidu];
for(int i = 0; i < weidu; i++){
// 创建prefab
GameObject o = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
o.transform.parent = transform;
o.transform.localScale = Vector3.one;
t.testids[i] = o.GetComponent<gridId>();
}
}
}

// 按照二维数组中的顺序,依次排开prefabs
void sortnow()
{
int row = 0;
int col = 0;

Bounds bon = NGUIMath.CalculateRelativeWidgetBounds(ids[0].testids[0].transform);
foreach (test t in ids) {
col = 0;
foreach(gridId ele in t.testids) {
float depth = ele.transform.localPosition.z;
ele.transform.localPosition = new Vector3(bon.size.x * col, -bon.size.y*row, depth);

col++;
}
row++;
}

transform.localPosition = new Vector3 (-bon.size.x / 2 * (weidu - 1),
bon.size.y / 2 * (ids.Length - 1), 0);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: