有事需要将SceneA中的一个对象在SceneB中使用,切换场景时候会将A场景对象全部卸载,此时就需要在切场景时候创建一个预设体,然后在SceneB中使用,动态的使用代码创建预设体,需要用到Unity的一个类PrefabUtility
代码如下
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
public class CreatePrefabInRunTime : MonoBehaviour {
void RunTimeCreatePrefab(GameObject obj, string prefabName)
{
string path = "Assets/Resources/CreatePrefabInRunTime/Prefabs/" + prefabName + ".prefab";
if (File.Exists (path)) {
Debug.Log ("is have");
}
// 如果不做路径判断,则会覆盖原路径中的文件
PrefabUtility.CreatePrefab (path, obj);
}
void OnGUI(){
if (GUILayout.Button ("create prefab")) {
GameObject obj = GameObject.Find ("TestPanel");
RunTimeCreatePrefab (obj, "test_panel_prefab");
}
}
}
其他
更多Blog请见:https://yiyuan1130.github.io/
Github地址:https://github.com/yiyuan1130

本文介绍如何在Unity中实现场景切换时保留特定对象,通过在运行时动态创建预设体,确保对象能够在不同场景间传递。利用PrefabUtility类,代码演示了创建预设体的具体步骤,包括路径检查和预设体保存。
1067

被折叠的 条评论
为什么被折叠?



