/// <summary>
    /// Set up everything necessary to preview a UI object.
    /// </summary>

    static bool SetupPreviewForUI(Camera cam, GameObject root, GameObject child, UISnapshotPoint point)
    {
        if (child.GetComponentInChildren <UIRect>() == null)
        {
            return(false);
        }

        if (child.GetComponent <UIPanel>() == null)
        {
            root.AddComponent <UIPanel>();
        }

        Bounds  bounds  = NGUIMath.CalculateAbsoluteWidgetBounds(child.transform);
        Vector3 size    = bounds.extents;
        float   objSize = size.magnitude;

        cam.transform.position = bounds.center;
        cam.cullingMask        = (1 << root.layer);

        if (point != null)
        {
            SetupSnapshotCamera(child, cam, point);
        }
        else
        {
            SetupSnapshotCamera(child, cam, objSize, Mathf.RoundToInt(Mathf.Max(size.x, size.y)), -100f, 100f);
        }
        NGUITools.ImmediatelyCreateDrawCalls(root);
        return(true);
    }
Beispiel #2
0
        void GeneratePreview(Item item, UISnapshotPoint point)
        {
            if (item == null || item.prefab == null)
            {
                return;
            }
            {
                string preview_path = Application.dataPath + "/" + Configure.ResPath + "Preview/" + item.prefab.name + ".png";
                if (File.Exists(preview_path))
                {
                    Texture texture = UIEditorHelper.LoadTextureInLocal(preview_path);
                    item.tex = texture;
                }
                else
                {
                    Texture Tex = UIEditorHelper.GetAssetPreview(item.prefab);
                    if (Tex != null)
                    {
                        DestroyTexture(item);
                        item.tex = Tex;
                        UIEditorHelper.SaveTextureToPNG(Tex, preview_path);
                    }
                }

                item.dynamicTex = false;
                return;
            }
        }
    /// <summary>
    /// Set up everything necessary to preview a UI object.
    /// </summary>

    static bool SetupPreviewFor3D(Camera cam, GameObject root, GameObject child, UISnapshotPoint point)
    {
        Renderer[] rens = child.GetComponentsInChildren <Renderer>();
        if (rens.Length == 0)
        {
            return(false);
        }

        Vector3 camDir   = new Vector3(-0.25f, -0.35f, -0.5f);
        Vector3 lightDir = new Vector3(-0.25f, -0.5f, -0.25f);

        camDir.Normalize();
        lightDir.Normalize();

        // Determine the bounds of the model
        Renderer ren    = rens[0];
        Bounds   bounds = ren.bounds;
        int      mask   = (1 << ren.gameObject.layer);

        for (int i = 1; i < rens.Length; ++i)
        {
            ren   = rens[i];
            mask |= (1 << ren.gameObject.layer);
            bounds.Encapsulate(ren.bounds);
        }

        // Set the camera's properties
        cam.cullingMask = mask;
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
        cam.isOrthoGraphic = true;
#else
        cam.orthographic = true;
#endif
        cam.transform.position = bounds.center;
        cam.transform.rotation = Quaternion.LookRotation(camDir);

        float objSize = bounds.size.magnitude;
        if (point != null)
        {
            SetupSnapshotCamera(child, cam, point);
        }
        else
        {
            SetupSnapshotCamera(child, cam, objSize, objSize * 0.4f, -objSize, objSize);
        }

        // Deactivate all scene lights
        DeactivateLights();

        // Create our own light
        GameObject lightGO = NGUITools.AddChild(root);
        Light      light   = lightGO.AddComponent <Light>();
        light.type               = LightType.Directional;
        light.shadows            = LightShadows.None;
        light.color              = Color.white;
        light.intensity          = 0.65f;
        light.transform.rotation = Quaternion.LookRotation(lightDir);
        light.cullingMask        = mask;
        return(true);
    }
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        SerializedProperty sp = NGUIEditorTools.DrawProperty("Orthographic", serializedObject, "isOrthographic");

        if (sp.hasMultipleDifferentValues)
        {
            NGUIEditorTools.DrawProperty("Ortho Size", serializedObject, "orthoSize");
            NGUIEditorTools.DrawProperty("Field of View", serializedObject, "fieldOfView");
        }
        else if (sp.boolValue)
        {
            NGUIEditorTools.DrawProperty("Ortho Size", serializedObject, "orthoSize");
        }
        else
        {
            NGUIEditorTools.DrawProperty("Field of View", serializedObject, "fieldOfView");
        }

        NGUIEditorTools.DrawProperty("Near Clip", serializedObject, "nearClip");
        NGUIEditorTools.DrawProperty("Far Clip", serializedObject, "farClip");

        serializedObject.ApplyModifiedProperties();

        GameObject prefab = GetPrefab();

        if (prefab == null)
        {
            EditorGUILayout.HelpBox("This script should be attached to a prefab that you expect to place into the Prefab Toolbar. " +
                                    "It simply makes it easier to adjust the snapshot camera's settings.", MessageType.Info);
        }
        else if (GUILayout.Button("Update Snapshot"))
        {
            // Invalidate this prefab's preview
            if (UIPrefabTool.instance != null)
            {
                UISnapshotPoint snapshot = target as UISnapshotPoint;

                if (snapshot.isOrthographic)
                {
                    target.name = "NGUI Snapshot Point " + snapshot.orthoSize;
                }
                else
                {
                    target.name = "NGUI Snapshot Point " + snapshot.nearClip + " " + snapshot.farClip + " " + snapshot.fieldOfView;
                }

                UIPrefabTool.instance.RegenerateTexture(prefab, snapshot);
                UIPrefabTool.instance.Repaint();
            }
        }
    }
Beispiel #5
0
 static public int get_isOrthographic(IntPtr l)
 {
     try {
         UISnapshotPoint self = (UISnapshotPoint)checkSelf(l);
         pushValue(l, true);
         pushValue(l, self.isOrthographic);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #6
0
 static public int get_fieldOfView(IntPtr l)
 {
     try {
         UISnapshotPoint self = (UISnapshotPoint)checkSelf(l);
         pushValue(l, true);
         pushValue(l, self.fieldOfView);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #7
0
    /// <summary>
    /// Generate an item preview for the specified item.
    /// </summary>

    void GeneratePreview(Item item, UISnapshotPoint point)
    {
        if (item == null || item.prefab == null)
        {
            return;
        }
        string path = "Assets/NGUI/Editor/Preview/" + item.prefab.name + ".png";

        item.tex        = File.Exists(path) ? (Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) : null;
        item.dynamicTex = false;
        return;
    }
Beispiel #8
0
    GameObject GetPrefab()
    {
        UISnapshotPoint point = target as UISnapshotPoint;

        // Root object of this prefab instance
        Transform  t  = point.transform.parent;
        GameObject go = PrefabUtility.FindPrefabRoot(t == null ? point.gameObject : t.gameObject);

        return(null);

        // Actual prefab
        //return PrefabUtility.GetCorrespondingObjectFromSource(go) as GameObject;
    }
Beispiel #9
0
    /// <summary>
    /// Re-generate the specified prefab's snapshot texture using the provided snapshot point's values.
    /// </summary>

    public void RegenerateTexture(GameObject prefab, UISnapshotPoint point)
    {
        for (int i = 0; i < mItems.size; ++i)
        {
            Item item = mItems[i];

            if (item.prefab == prefab)
            {
                GeneratePreview(item, point);
                RectivateLights();
                break;
            }
        }
    }
Beispiel #10
0
 static public int set_farClip(IntPtr l)
 {
     try {
         UISnapshotPoint self = (UISnapshotPoint)checkSelf(l);
         System.Single   v;
         checkType(l, 2, out v);
         self.farClip = v;
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #11
0
 static public int set_isOrthographic(IntPtr l)
 {
     try {
         UISnapshotPoint self = (UISnapshotPoint)checkSelf(l);
         System.Boolean  v;
         checkType(l, 2, out v);
         self.isOrthographic = v;
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #12
0
 static public int set_thumbnail(IntPtr l)
 {
     try {
         UISnapshotPoint       self = (UISnapshotPoint)checkSelf(l);
         UnityEngine.Texture2D v;
         checkType(l, 2, out v);
         self.thumbnail = v;
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #13
0
 static public int set_fieldOfView(IntPtr l)
 {
     try {
         UISnapshotPoint self = (UISnapshotPoint)checkSelf(l);
         System.Int32    v;
         checkType(l, 2, out v);
         self.fieldOfView = v;
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
    GameObject GetPrefab()
    {
        UISnapshotPoint point = target as UISnapshotPoint;

        // Root object of this prefab instance
        GameObject go = PrefabUtility.FindPrefabRoot(point.gameObject);

        if (go == null)
        {
            return(null);
        }

        // Actual prefab
        return(PrefabUtility.GetCorrespondingObjectFromSource(go) as GameObject);
    }
    GameObject GetPrefab()
    {
        UISnapshotPoint point = target as UISnapshotPoint;

        // Root object of this prefab instance
        Transform  t  = point.transform.parent;
        GameObject go = PrefabUtility.FindPrefabRoot(t == null ? point.gameObject : t.gameObject);

        if (go == null)
        {
            return(null);
        }

        // Actual prefab
        return(PrefabUtility.GetPrefabParent(go) as GameObject);
    }
Beispiel #16
0
    GameObject GetPrefab()
    {
        UISnapshotPoint point = target as UISnapshotPoint;

        // Root object of this prefab instance
        Transform  t  = point.transform.parent;
        GameObject go = PrefabUtility.FindPrefabRoot(t == null ? point.gameObject : t.gameObject);

        if (go == null)
        {
            return(null);
        }

        // Actual prefab
#if UNITY_2018
        return(PrefabUtility.GetCorrespondingObjectFromSource(go) as GameObject);
#else
        return(PrefabUtility.GetPrefabParent(go) as GameObject);
#endif
    }
Beispiel #17
0
    /// <summary>
    /// GetComponentInChildren doesn't work on prefabs.
    /// </summary>

    static UISnapshotPoint GetSnapshotPoint(Transform t)
    {
        UISnapshotPoint point = t.GetComponent <UISnapshotPoint>();

        if (point != null)
        {
            return(point);
        }

        for (int i = 0, imax = t.childCount; i < imax; ++i)
        {
            Transform c = t.GetChild(i);
            point = GetSnapshotPoint(c);
            if (point != null)
            {
                return(point);
            }
        }
        return(null);
    }
Beispiel #18
0
    /// <summary>
    /// Set up the camera using the provided snapshot point's values.
    /// </summary>

    static void SetupSnapshotCamera(GameObject go, Camera cam, UISnapshotPoint point)
    {
        Vector3    pos = point.transform.localPosition;
        Quaternion rot = point.transform.localRotation;
        Transform  t   = go.transform;

        if (t.parent != null)
        {
            pos = t.parent.TransformPoint(pos);
            rot = t.parent.rotation * rot;
        }

        cam.transform.position = pos;
        cam.transform.rotation = rot;
        cam.orthographic       = point.isOrthographic;
        cam.nearClipPlane      = point.nearClip;
        cam.farClipPlane       = point.farClip;
        cam.orthographicSize   = point.orthoSize;
        cam.fieldOfView        = point.fieldOfView;
    }
    /// <summary>
    /// Set up the camera using the provided snapshot point's values.
    /// </summary>

    static void SetupSnapshotCamera(GameObject go, Camera cam, UISnapshotPoint point)
    {
        var pos = point.transform.localPosition;
        var rot = point.transform.localRotation;
        var t   = go.transform;

        if (t.parent != null)
        {
            pos = t.parent.TransformPoint(pos);
            rot = t.parent.rotation * rot;
        }

        cam.transform.position = pos;
        cam.transform.rotation = rot;
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
        cam.isOrthoGraphic = point.isOrthographic;
#else
        cam.orthographic = point.isOrthographic;
#endif
        cam.nearClipPlane    = point.nearClip;
        cam.farClipPlane     = point.farClip;
        cam.orthographicSize = point.orthoSize;
        cam.fieldOfView      = point.fieldOfView;
    }
Beispiel #20
0
    /// <summary>
    /// Generate an item preview for the specified item.
    /// </summary>

    void GeneratePreview(Item item, UISnapshotPoint point)
    {
        if (item == null || item.prefab == null)
        {
            return;
        }

        // For some reason Unity 5 doesn't seem to support render textures at edit time while Unity 4 does...
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
        if (point == null)
        {
            point = GetSnapshotPoint(item.prefab.transform);
        }

        if (point != null && point.thumbnail != null)
        {
            // Explicitly chosen thumbnail
            item.tex        = point.thumbnail;
            item.dynamicTex = false;
            return;
        }
        else if (!UnityEditorInternal.InternalEditorUtility.HasPro())
#endif
        {
            // Render textures only work in Unity Pro
            string path = "Assets/NGUI/Editor/Preview/" + item.prefab.name + ".png";
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
            item.tex = File.Exists(path) ? (Texture2D)Resources.LoadAssetAtPath(path, typeof(Texture2D)) : null;
#else
            item.tex = File.Exists(path) ? (Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) : null;
#endif
            item.dynamicTex = false;
            return;
        }
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
        int dim = (cellSize - 4) * 2;

        // Asset Preview-based approach is unreliable, and most of the time fails to provide a texture.
        // Sometimes it even throws null exceptions.
        //item.tex = AssetPreview.GetAssetPreview(item.prefab);
        //item.dynamicTex = false;
        //if (item.tex != null) return;

        // Let's create a basic scene
        GameObject root  = EditorUtility.CreateGameObjectWithHideFlags("Preview Root", HideFlags.HideAndDontSave);
        GameObject camGO = EditorUtility.CreateGameObjectWithHideFlags("Preview Camera", HideFlags.HideAndDontSave, typeof(Camera));

        // Position it far away so that it doesn't interfere with existing objects
        root.transform.position = new Vector3(0f, 0f, 10000f);
        root.layer = item.prefab.layer;

        // Set up the camera
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
        Camera cam = camGO.camera;
        cam.isOrthoGraphic = true;
#else
        Camera cam = camGO.GetComponent <Camera>();
        cam.orthographic = true;
#endif
        cam.renderingPath   = RenderingPath.Forward;
        cam.clearFlags      = CameraClearFlags.Skybox;
        cam.backgroundColor = new Color(0f, 0f, 0f, 0f);
        cam.targetTexture   = (item.tex as RenderTexture);
        cam.enabled         = false;

        // Finally instantiate the prefab as a child of the root
        GameObject child = NGUITools.AddChild(root, item.prefab);

        // Try to find the snapshot point script
        if (point == null)
        {
            point = child.GetComponentInChildren <UISnapshotPoint>();
        }

        // If there is a UIRect present (widgets or panels) then it's an NGUI object
        RenderTexture rt = (SetupPreviewForUI(cam, root, child, point) || SetupPreviewFor3D(cam, root, child, point)) ?
                           cam.RenderToTexture(dim, dim) : null;

        // Did we have a different render texture? Get rid of it.
        if (item.tex != rt && item.tex != null && item.dynamicTex)
        {
            NGUITools.DestroyImmediate(item.tex);
            item.tex        = null;
            item.dynamicTex = false;
        }

        // Do we have a new render texture? Assign it.
        if (rt != null)
        {
            item.tex        = rt;
            item.dynamicTex = true;
        }

        // Clean up everything
        DestroyImmediate(camGO);
        DestroyImmediate(root);
#endif
    }
Beispiel #21
0
	/// <summary>
	/// Set up everything necessary to preview a UI object.
	/// </summary>

	static bool SetupPreviewFor3D (Camera cam, GameObject root, GameObject child, UISnapshotPoint point)
	{
		Renderer[] rens = child.GetComponentsInChildren<Renderer>();
		if (rens.Length == 0) return false;

		Vector3 camDir = new Vector3(-0.25f, -0.35f, -0.5f);
		Vector3 lightDir = new Vector3(-0.25f, -0.5f, -0.25f);

		camDir.Normalize();
		lightDir.Normalize();

		// Determine the bounds of the model
		Renderer ren = rens[0];
		Bounds bounds = ren.bounds;
		int mask = (1 << ren.gameObject.layer);

		for (int i = 1; i < rens.Length; ++i)
		{
			ren = rens[i];
			mask |= (1 << ren.gameObject.layer);
			bounds.Encapsulate(ren.bounds);
		}

		// Set the camera's properties
		cam.cullingMask = mask;
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
		cam.isOrthoGraphic = true;
#else
		cam.orthographic = true;
#endif
		cam.transform.position = bounds.center;
		cam.transform.rotation = Quaternion.LookRotation(camDir);

		float objSize = bounds.size.magnitude;
		if (point != null) SetupSnapshotCamera(child, cam, point);
		else SetupSnapshotCamera(child, cam, objSize, objSize * 0.4f, -objSize, objSize);

		// Deactivate all scene lights
		DeactivateLights();

		// Create our own light
		GameObject lightGO = NGUITools.AddChild(root);
		Light light = lightGO.AddComponent<Light>();
		light.type = LightType.Directional;
		light.shadows = LightShadows.None;
		light.color = Color.white;
		light.intensity = 0.65f;
		light.transform.rotation = Quaternion.LookRotation(lightDir);
		light.cullingMask = mask;
		return true;
	}
Beispiel #22
0
	/// <summary>
	/// Set up the camera using the provided snapshot point's values.
	/// </summary>

	static void SetupSnapshotCamera (GameObject go, Camera cam, UISnapshotPoint point)
	{
		Vector3 pos = point.transform.localPosition;
		Quaternion rot = point.transform.localRotation;
		Transform t = go.transform;

		if (t.parent != null)
		{
			pos = t.parent.TransformPoint(pos);
			rot = t.parent.rotation * rot;
		}

		cam.transform.position = pos;
		cam.transform.rotation = rot;
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
		cam.isOrthoGraphic = point.isOrthographic;
#else
		cam.orthographic = point.isOrthographic;
#endif
		cam.nearClipPlane = point.nearClip;
		cam.farClipPlane = point.farClip;
		cam.orthographicSize = point.orthoSize;
		cam.fieldOfView = point.fieldOfView;
	}
Beispiel #23
0
	/// <summary>
	/// Set up everything necessary to preview a UI object.
	/// </summary>

	static bool SetupPreviewForUI (Camera cam, GameObject root, GameObject child, UISnapshotPoint point)
	{
		if (child.GetComponentInChildren<UIRect>() == null) return false;

		if (child.GetComponent<UIPanel>() == null)
			root.AddComponent<UIPanel>();

		Bounds bounds = NGUIMath.CalculateAbsoluteWidgetBounds(child.transform);
		Vector3 size = bounds.extents;
		float objSize = size.magnitude;

		cam.transform.position = bounds.center;
		cam.cullingMask = (1 << root.layer);

		if (point != null) SetupSnapshotCamera(child, cam, point);
		else SetupSnapshotCamera(child, cam, objSize, Mathf.RoundToInt(Mathf.Max(size.x, size.y)), -100f, 100f);
		NGUITools.ImmediatelyCreateDrawCalls(root);
		return true;
	}
Beispiel #24
0
	/// <summary>
	/// Generate an item preview for the specified item.
	/// </summary>

	void GeneratePreview (Item item, UISnapshotPoint point)
	{
		if (item == null || item.prefab == null) return;

		if (point == null) point = GetSnapshotPoint(item.prefab.transform);

		if (point != null && point.thumbnail != null)
		{
			Debug.Log(2);
			// Explicitly chosen thumbnail
			item.tex = point.thumbnail;
			item.dynamicTex = false;
			return;
		}
		else if (!UnityEditorInternal.InternalEditorUtility.HasPro())
		{
			// Render textures only work in Unity Pro
			string path = "Assets/NGUI/Editor/Preview/" + item.prefab.name + ".png";
			item.tex = File.Exists(path) ? (Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) : null;
			item.dynamicTex = false;
			return;
		}

		int dim = (cellSize - 4) * 2;

		// Asset Preview-based approach is unreliable, and most of the time fails to provide a texture.
		// Sometimes it even throws null exceptions.
		//item.tex = AssetPreview.GetAssetPreview(item.prefab);
		//item.dynamicTex = false;
		//if (item.tex != null) return;

		// Let's create a basic scene
		GameObject root = EditorUtility.CreateGameObjectWithHideFlags(
				"Preview Root", HideFlags.HideAndDontSave);

		GameObject camGO = EditorUtility.CreateGameObjectWithHideFlags(
			"Preview Camera", HideFlags.HideAndDontSave, typeof(Camera));

		// Position it far away so that it doesn't interfere with existing objects
		root.transform.position = new Vector3(0f, 0f, 10000f);
		root.layer = item.prefab.layer;

		// Set up the camera
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
		Camera cam = camGO.camera;
		cam.isOrthoGraphic = true;
#else
		Camera cam = camGO.GetComponent<Camera>();
		cam.orthographic = true;
#endif
		cam.renderingPath = RenderingPath.Forward;
		cam.clearFlags = CameraClearFlags.Skybox;
		cam.backgroundColor = new Color(0f, 0f, 0f, 0f);
		cam.targetTexture = (item.tex as RenderTexture);
		cam.enabled = false;

		// Finally instantiate the prefab as a child of the root
		GameObject child = NGUITools.AddChild(root, item.prefab);

		// Try to find the snapshot point script
		if (point == null) point = child.GetComponentInChildren<UISnapshotPoint>();

		// If there is a UIRect present (widgets or panels) then it's an NGUI object
		RenderTexture rt = (SetupPreviewForUI(cam, root, child, point) || SetupPreviewFor3D(cam, root, child, point)) ?
			cam.RenderToTexture(dim, dim) : null;

		// Did we have a different render texture? Get rid of it.
		if (item.tex != rt && item.tex != null && item.dynamicTex)
		{
			NGUITools.DestroyImmediate(item.tex);
			item.tex = null;
			item.dynamicTex = false;
		}

		// Do we have a new render texture? Assign it.
		if (rt != null)
		{
			item.tex = rt;
			item.dynamicTex = true;
		}

		// Clean up everything
		DestroyImmediate(camGO);
		DestroyImmediate(root);
	}
Beispiel #25
0
	/// <summary>
	/// Re-generate the specified prefab's snapshot texture using the provided snapshot point's values.
	/// </summary>

	public void RegenerateTexture (GameObject prefab, UISnapshotPoint point)
	{
		for (int i = 0; i < mItems.size; ++i)
		{
			Item item = mItems[i];

			if (item.prefab == prefab)
			{
				GeneratePreview(item, point);
				RectivateLights();
				break;
			}
		}
	}
Beispiel #26
0
    /// <summary>
    /// Generate an item preview for the specified item.
    /// </summary>

    void GeneratePreview(Item item, UISnapshotPoint point)
    {
        if (item == null || item.prefab == null)
        {
            return;
        }

        // Render textures only work in Unity Pro
        if (!UnityEditorInternal.InternalEditorUtility.HasPro())
        {
            item.tex        = LoadPreview(item);
            item.dynamicTex = true;
            return;
        }

        int dim = (cellSize - 4) * 2;

        // Asset Preview-based approach is unreliable, and most of the time fails to provide a texture.
        // Sometimes it even throws null exceptions.
        //item.tex = AssetPreview.GetAssetPreview(item.prefab);
        //item.dynamicTex = false;
        //if (item.tex != null) return;

        // Let's create a basic scene
        GameObject root = EditorUtility.CreateGameObjectWithHideFlags(
            "Preview Root", HideFlags.HideAndDontSave);

        GameObject camGO = EditorUtility.CreateGameObjectWithHideFlags(
            "Preview Camera", HideFlags.HideAndDontSave, typeof(Camera));

        // Position it far away so that it doesn't interfere with existing objects
        root.transform.position = new Vector3(0f, 0f, 10000f);
        root.layer = item.prefab.layer;

        // Set up the camera
        Camera cam = camGO.camera;

        cam.renderingPath   = RenderingPath.Forward;
        cam.clearFlags      = CameraClearFlags.Skybox;
        cam.isOrthoGraphic  = true;
        cam.backgroundColor = new Color(0f, 0f, 0f, 0f);
        cam.targetTexture   = (item.tex as RenderTexture);
        cam.enabled         = false;

        // Finally instantiate the prefab as a child of the root
        GameObject child = NGUITools.AddChild(root, item.prefab);

        // Try to find the snapshot point script
        if (point == null)
        {
            point = child.GetComponentInChildren <UISnapshotPoint>();
        }

        // If there is a UIRect present (widgets or panels) then it's an NGUI object
        RenderTexture rt = (SetupPreviewForUI(cam, root, child, point) || SetupPreviewFor3D(cam, root, child, point)) ?
                           cam.RenderToTexture(dim, dim) : null;

        // Did we have a different render texture? Get rid of it.
        if (item.tex != rt && item.tex != null && item.dynamicTex)
        {
            NGUITools.DestroyImmediate(item.tex);
            item.tex        = null;
            item.dynamicTex = false;
        }

        // Do we have a new render texture? Assign it.
        if (rt != null)
        {
            item.tex        = rt;
            item.dynamicTex = true;
        }

        // Clean up everything
        DestroyImmediate(camGO);
        DestroyImmediate(root);
    }
Beispiel #27
0
    /// <summary>
    /// Generate an item preview for the specified item.
    /// </summary>

    void GeneratePreview(Item item, UISnapshotPoint point)
    {
        if (item == null || item.prefab == null)
        {
            return;
        }

        int           dim = (cellSize - 4) * 2;
        RenderTexture rt  = (item.tex as RenderTexture);

        // If the dimensions have changed, we will need to create a new render texture
        if (rt != null && item.dynamicTex && (item.tex.width != dim || item.tex.height != dim))
        {
            DestroyImmediate(item.tex);
        }

#if UNITY_3_5
        // Unfortunately Unity 3.5 doesn't seem to support a proper way of doing any of this
        item.tex        = null;
        item.dynamicTex = false;
#else
        // Asset Preview-based approach is unreliable, and most of the time fails to provide a texture.
        // Sometimes it even throws null exceptions.
        //item.tex = AssetPreview.GetAssetPreview(item.prefab);
        //item.dynamicTex = false;
        //if (item.tex != null) return;

        // Let's create a basic scene
        GameObject root = EditorUtility.CreateGameObjectWithHideFlags(
            "Preview Root", HideFlags.HideAndDontSave);

        GameObject camGO = EditorUtility.CreateGameObjectWithHideFlags(
            "Preview Camera", HideFlags.HideAndDontSave, typeof(Camera));

        // Position it far away so that it doesn't interfere with existing objects
        root.transform.position = new Vector3(0f, 0f, 10000f);
        root.layer = item.prefab.layer;

        // Set up the camera
        Camera cam = camGO.GetComponent <Camera>();
        cam.renderingPath   = RenderingPath.Forward;
        cam.clearFlags      = CameraClearFlags.Skybox;
        cam.orthographic    = true;
        cam.backgroundColor = new Color(0f, 0f, 0f, 0f);

        // Set up the render texture for the camera
        if (rt == null)
        {
            rt              = new RenderTexture(dim, dim, 1);
            rt.hideFlags    = HideFlags.HideAndDontSave;
            rt.generateMips = false;
            rt.format       = RenderTextureFormat.ARGB32;
            rt.filterMode   = FilterMode.Trilinear;
            rt.anisoLevel   = 4;

            item.tex        = rt;
            item.dynamicTex = true;
        }
        cam.targetTexture = rt;

        // Finally instantiate the prefab as a child of the root
        GameObject child = NGUITools.AddChild(root, item.prefab);

        // Try to find the snapshot point script
        if (point == null)
        {
            point = child.GetComponentInChildren <UISnapshotPoint>();
        }

        // If there is a UIRect present (widgets or panels) then it's an NGUI object
        if (SetupPreviewForUI(cam, root, child, point) ||
            SetupPreviewFor3D(cam, root, child, point))
        {
            cam.Render();
        }

        // Clean up everything
        DestroyImmediate(camGO);
        DestroyImmediate(root);
#endif
    }