HideFlags为枚举类,用于控制object对象的销毁方式及其在检视面板中的可视性。本博客对HideFlags类枚举成员的功能及其使用方法进行较为详细的说明。
一、HideFlags枚举成员
枚举类HideFlags涉及的枚举成员由DontSave、HideAndDontSave、HideInHierarchy、HideInInspector、None和NotEditable。
1、DontSave属性:保留对象到新场景
(1)功能说明
此属性的功能室用来设置是否将Object对象保留到新的场景中,如果使用HideFlags、DontSave,则Object对象将在新场景中被保留下来,对其使用说明如下:
- 如果GameObject对象被HideFlags.DontSava标识,则在新Scene中GameObject的所有组件将被保留下来,但其子类GameObject对象不会被保留到新Scene中。
- 不可以对GameObject对象的某个组件如Transform进行HideFlags.DontSave标识,否则无效
- 及时程序已经退出,被HideFlags.DontSave标识的独享,在不需要或程序退出时需要使用DestroyImmediate手动销毁
(2)代码实现
①DontSave_test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontSave_test : MonoBehaviour
{
public GameObject go;
public Transform t;
void Start()
{
//GameObject对象使用HideFlags.DontSave可以在新scene中被保留
go.hideFlags = HideFlags.DontSave;
GameObject P1 = GameObject.CreatePrimitive(PrimitiveType.Plane);
P1.hideFlags = HideFlags.DontSave;
//不可以在GameObject的组件设置HideFlags.DontSave,否则无效
Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform;
tf.hideFlags = HideFlags.DontSave;
//导入名为newScene_unity的新scene
Application.LoadLevel("new Scene2 unity");
}
}
在这段代码中,分别对场景中GameObject对象go、新创建的GameObject独享Pl和新实例化的Transform实例tf的hideFlags属性设置为HideFlags.DontSave,然后导入名为newScene2_unity的新场景。
②newScene2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class newScene2 : MonoBehaviour
{
GameObject cube, plane;
void Start()
{
Debug.Log("这是newScene2!");
}
//当程序退出时用DestroyImmediate()销毁被HideFlags.DontSave标识的对象
//否则及时程序已经退出,被HideFlags.DontSave标识的对象毅然在Hierarchy面板中
//即每运行一次程序就会产生多余对象,造成内存泄漏
void OnApplicationQuit()
{
cube = GameObject.Find("Cube0");
plane = GameObject.Find("Plane");
if (cube)
{
Debug.Log("Cube0 DestroyImmediate");
DestroyImmediate(cube);
}
if (plane)
{
Debug.Log("Plane DestoryImmediate");
DestroyImmediate(plane);
}
}
}
notes:首先声明了两个GameObject类型的变量cube和plane,然后再OnApplicationQuit()方法中查找当前场景中是否存在名为Cube0和Plane的GameObject对象,如果存在,则在程序退出时将它们立即销毁。
图a位程序启动前场景中的物体,图b为程序启动后场景中的物体,图c为在程序退出时未将场景中被保留的物体销毁时的结果(即把场景newScene2脚本中OnApplicationQuit()中的代码注释掉后程序的运行结果)。如果在程序退出时销毁了被ideFlags.DontSave标识的对象,则程序退出后状态如图a所示