Calendar
| Mo | Tu | We | Th | Fr | Sa | Su |
|---|
| 29 | 30 | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 10 | 11 | 12 | | 13 | 14 | 15 | 16 | 17 | 18 | 19 | | 20 | 21 | 22 | 23 | 24 | 25 | 26 | | 27 | 28 | 29 | 30 | 31 | 1 | 2 | | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Archive
- 2002
- 2003
- 2004
- 2005
- 2006
- 2007
- 2008
- 2009
- 2010
- 2011
- 2012
- 2013
|
Source –> https://gist.github.com/chkn/4748252
using System;
using System.Linq;
public static class JSON
{
public static string Stringify (object obj)
{
string str;
if (obj == null) return "null";
if (obj is ValueType) return obj.ToString ().ToLowerInvariant ();
if ((str = obj as string) != null) return System.Text.RegularExpressions.Regex.Escape (str);
// assume it's a POCO
return "{" + string.Join (",",
from p in obj.GetType ().GetProperties ()
let json = (JSONAttribute) p.GetCustomAttributes (typeof (JSONAttribute), true).FirstOrDefault ()
where json != null
select "\"" + (json.Key ?? p.Name) + "\":" + Stringify (p.GetValue (obj, null))
) + "}";
}
}
public class JSONAttribute : Attribute
{
public string Key { get; set; }
public JSONAttribute () {}
public JSONAttribute (string key) { Key = key; }
}
481a00a4-49ee-4b07-a9ed-bc17792e0620|0|.0
/// <summary>
/// Determines if this rectangle intersects with rect.
/// </summary>
/// <param name="rect">
/// The rectangle to test.
/// </param>
/// <returns>
/// This method returns true if there is any intersection, otherwise false.
/// </returns>
public bool Intersects(RectangleF rect)
{
return !((this.X > rect.Right) || (this.Right < rect.Left) || (this.Y > rect.Bottom) || (this.Bottom < rect.Top));
}
/// <summary>
/// Replaces this RectangleF with the intersection of itself and the specified RectangleF.
/// </summary>
/// <param name="rect">
/// The RectangleF with which to intersect.
/// </param>
public void Intersect(RectangleF rect)
{
this.X = Math.Max(this.Left, rect.Left);
this.Y = Math.Max(this.Top, rect.Top);
this.Width = Math.Min(this.Right, rect.Right) - this.X;
this.Height = Math.Min(this.Bottom, rect.Bottom) - this.Y;
}
/// <summary>
/// Returns a third RectangleF structure that represents the intersection of two other RectangleF structures.
/// If there is no intersection, an empty RectangleF is returned.
/// </summary>
/// <param name="a">
/// A rectangle to intersect.
/// </param>
/// <param name="b">
/// B rectangle to intersect.
/// </param>
/// <returns>
/// A RectangleF that represents the intersection of a and b.
/// </returns>
public static RectangleF Intersect(RectangleF a, RectangleF b)
{
float x = Math.Max((sbyte)a.X, (sbyte)b.X);
float num2 = Math.Min(a.X + a.Width, b.X + b.Width);
float y = Math.Max((sbyte)a.Y, (sbyte)b.Y);
float num4 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if ((num2 >= x) && (num4 >= y))
{
return new RectangleF(x, y, num2 - x, num4 - y);
}
return Empty;
}
05946fd4-7017-4962-94da-f20f0e53ca87|0|.0
I’ve recently come across what initially seems like a bug with the Unity 4 editor. it involves the use of the Resources.Load method from within a class marked InitializeOnLoad.
Take the fallowing example code …
namespace CBX.CoreProjectCode
{
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class EditorInitialization
{
static EditorInitialization()
{
LoadData(); // this will fail to see the test.txt file in the resource folder
}
private static void LoadData()
{
// try to load data
var data = Resources.Load("test", typeof(TextAsset)) as TextAsset;
if (data == null)
{
Debug.LogWarning("No data found");
return;
}
Debug.Log(data.text);
}
}
}
After Unity compiles the scripts it will invoke any static constructors of classes marked with InitializeOnLoad. But at this point I suspect that Unity has not yet identified assets you have within any Resources folders. When the class constructor calls the Resources.Load method it will fail to read the test.txt resource file and return a warning message out to the console.
What you could do at this point is right click the “Assets” folder in the project window and select “Reimport”. Unity will reimport the assets and again call classes marked with InitializeOnLoad. But this time Resources.load will successfully load the test.txt file resource and display it’s contents out to the Unity console window.
One work around to this is to hook into the EditorApplication.update callback and make a call to the LoadData method from there. An example is provided below …
namespace CBX.CoreProjectCode
{
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class EditorInitialization
{
private static bool ranOnce;
static EditorInitialization()
{
EditorApplication.update += RunCallbacks;
}
private static void RunCallbacks()
{
if (!ranOnce)
{
// this will see the test.txt file in the Resource folder and display
// its contents
LoadData();
ranOnce = true;
// return or don't it’s up to you
return;
}
// do some work here
}
private static void LoadData()
{
var data = Resources.Load("test", typeof(TextAsset)) as TextAsset;
if (data == null)
{
Debug.LogWarning("No data found");
return;
}
Debug.Log(data.text);
}
}
}
Again I am unsure whether this is an actual bug or not but I have submitted a Unity bug report anyway just in case. Here is a link to the my bug report https://fogbugz.unity3d.com/default.asp?525005_eroka98ru2v4netm
0734807f-c506-419f-b84a-b313215404c0|0|.0
/// <summary>
/// Blends two colors together.
/// </summary>
/// <param name="color">
/// The source color.
/// </param>
/// <param name="src">
/// The blend color.
/// </param>
/// <returns>
/// Returns the result as a <see cref="Color"/> type.
/// </returns>
/// <remarks>
/// From Wikipedia https://en.wikipedia.org/wiki/Alpha_compositing -> "Alpha blending"
/// </remarks>
public static Color Blend(this Color color, Color src)
{
float sr = src.R / 255f;
float sg = src.G / 255f;
float sb = src.B / 255f;
float sa = src.A / 255f;
float dr = color.R / 255f;
float dg = color.G / 255f;
float db = color.B / 255f;
float da = color.A / 255f;
float oa = sa + (da * (1 - sa));
float r = ((sr * sa) + ((dr * da) * (1 - sa))) / oa;
float g = ((sg * sa) + ((dg * da) * (1 - sa))) / oa;
float b = ((sb * sa) + ((db * da) * (1 - sa))) / oa;
float a = oa;
return new Color((byte)(r * 255), (byte)(g * 255), (byte)(b * 255), (byte)(a * 255));
}
9bbf3709-4044-433c-a98f-3f1cf8767be4|0|.0
The code below allows you to scale a GameObject transform to a specific size along the x & z axis by taking into account the GameObjects renderer bounds if a renderer component is attached. /// <summary>
/// Scales a transform to specific dimensions along the x & z axis.
/// </summary>
/// <param name="transform">
/// Reference to the transform to scale.
/// </param>
/// <param name="width">The width along the x axis that represents the target size.</param>
/// <param name="height">The height along the z axis that represents the target size.</param>
public static void ScaleTransform(Transform transform, float width, float height)
{
// get bounds of the prefab
var bounds = new Bounds();
var encapsulate = false;
if (!Utilities.Helpers.GetBoundWithChildren(transform, ref bounds, ref encapsulate))
{
return;
}
// get minimum size from the size dimensions
var min = Mathf.Min(width, height);
// get the maximum x or z size of the transform
var max = Mathf.Max(bounds.size.x, bounds.size.z);
// calculate the scale factor
var scaleFactor = min / max;
// apply scaling to the transform
transform.localScale *= scaleFactor;
}
/// <summary>
/// Gets the rendering bounds of the transform.
/// </summary>
/// <param name="transform">The game object to get the bounding box for.</param>
/// <param name="pBound">The bounding box reference that will </param>
/// <param name="encapsulate">Used to determine if the first bounding box to be
/// calculated should be encapsulated into the <see cref="pBound"/> argument.</param>
/// <returns>Returns true if at least one bounding box was calculated.</returns>
public static bool GetBoundWithChildren(Transform transform, ref Bounds pBound, ref bool encapsulate)
{
var didOne = false;
// get 'this' bound
if (transform.gameObject.renderer != null)
{
var bound = transform.gameObject.renderer.bounds;
if (encapsulate)
{
pBound.Encapsulate(bound.min);
pBound.Encapsulate(bound.max);
}
else
{
pBound.min = bound.min;
pBound.max = bound.max;
encapsulate = true;
}
didOne = true;
}
// union with bound(s) of any/all children
foreach (Transform child in transform)
{
if (GetBoundWithChildren(child, ref pBound, ref encapsulate))
{
didOne = true;
}
}
return didOne;
}
f69b0e05-e860-408e-b328-6ed8c16af785|0|.0
Using the Undo.IncrementCurrentEventIndex allows your editor scripts to undo a single action rather then have unity undo many actions that may have occurred in rapid succession. Place the code below into a “Editor” folder for it to run. The “create object” button will create 10 cubes and call Undo.RegisterCreatedObjectUndo for each of them. Click this button then press ctrl+z to undo all of the objects that were created. The second button “create single object” will also create 10 cubes but will also call the Undo.IncrementCurrentEventIndex method notifying unity that each object that is created should have a separate undo action. Click “create single object” to create 10 cubes then press ctrl+z to undo each object creation individually. NOTE: At the time of this writing the unity documentation does not have information on the Undo.IncrementCurrentEventIndex method and searching for it also comes back with zero results. using UnityEngine;
using UnityEditor;
public class UndoTest : EditorWindow
{
public void OnGUI()
{
if (GUILayout.Button("create object"))
{
this.Create(false);
}
if (GUILayout.Button("create single object"))
{
this.Create(true);
}
GUILayout.Label("use ctrl+z to undo each action");
}
private void Create(bool single)
{
for (int i = 0; i < 10; i++)
{
if (single)
{
Undo.IncrementCurrentEventIndex();
}
var obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
obj.transform.position = new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), Random.Range(-10, 10));
Undo.RegisterCreatedObjectUndo(obj, "create " + obj.name);
}
}
[MenuItem("CBX/UndoTest")]
public static void ShowWindow()
{
GetWindow<UndoTest>("UndoTest").Show();
}
}
4f103dda-9a8c-4def-8268-277c6be61937|0|.0
/// <summary>
/// Packs color components into a <see cref="uint"/> type.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <param name="a">The alpha component.</param>
/// <returns>Returns a uint representing the color.</returns>
public static uint Pack(int r, int g, int b, int a)
{
return (((uint)r & 0xff)) | (((uint)g & 0xff) << 8) | (((uint)b & 0xff) << 16) | (((uint)a & 0xff) << 24);
}
/// <summary>
/// Unpacks a <see cref="uint"/> type into a color type.
/// </summary>
/// <param name="value">The packed color value to unpack.</param>
/// <returns>Returns a color type from the unpacked values.</returns>
public static Color Unpack(uint value)
{
var r = (byte)(value);
var g = (byte)(value >> 8);
var b = (byte)(value >> 16);
var a = (byte)(value >> 24);
return new Color(r, g, b, a);
}
a7e4cdca-282e-4daf-964a-dcc5103a7479|0|.0
If your Unity code requires conditional compilation symbols to be present this bit of code may come in handy. After unity compiles your scripts it executes any classes that have the InitializeOnLoad attribute. You can call the SetupConditionalCompilation method provided in the code snippet below to ensure that the conditional compilation symbols persist in your unity project. If a symbol was not present and was added it will write out a notification in the unity console.  [InitializeOnLoad]
public class GridMappingSetup
{
static GridMappingSetup()
{
var types = new[] { BuildTargetGroup.Standalone, BuildTargetGroup.WebPlayer };
var toInclude = new[] { "CBXControls", "GridMapping", "QuickTools", "ToolService", "TileMaterialCreation" };
SetupConditionalCompilation(types, toInclude);
}
}
public static void SetupConditionalCompilation(BuildTargetGroup[] platformTargets, string[] symbolsToInclude)
{
foreach (var type in platformTargets)
{
var hasEntry = new bool[symbolsToInclude.Length];
var conditionals = PlayerSettings.GetScriptingDefineSymbolsForGroup(type).Trim();
var parts = conditionals.Split(';');
var changed = false;
foreach (var part in parts)
{
for (int i = 0; i < symbolsToInclude.Length; i++)
{
if (part.Trim() == symbolsToInclude[i].Trim())
{
hasEntry[i] = true;
break;
}
}
}
for (int i = 0; i < hasEntry.Length; i++)
{
if (!hasEntry[i])
{
conditionals += (String.IsNullOrEmpty(conditionals) ? String.Empty : ";") + symbolsToInclude[i];
changed = true;
}
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(type, conditionals);
if (changed)
{
Debug.Log(String.Format("Updated player conditional compilation symbols for {0}: {1}", type, conditionals));
}
}
}
b8442cb9-a285-4e8e-b809-01378b846cbd|0|.0
Here is a C# script for visualizing render bounds. Just attach it to a game object and it will draw the render bounds of the game object and all it’s children. Handy for debugging!  public class RendererBoundsGizmo : MonoBehaviour
{
public bool ShowCenter;
public Color Color = Color.white;
public bool DrawCube = true;
public bool DrawSphere = false;
/// <summary>
/// When the game object is selected this will draw the gizmos
/// </summary>
/// <remarks>Only called when in the Unity editor.</remarks>
private void OnDrawGizmosSelected()
{
Gizmos.color = this.Color;
// get renderer bonding box
var bounds = new Bounds();
var initBound = false;
if (CBX.Utilities.Helpers.GetBoundWithChildren(this.transform, ref bounds, ref initBound))
{
if (this.DrawCube)
{
Gizmos.DrawWireCube(bounds.center, bounds.size);
}
if (this.DrawSphere)
{
Gizmos.DrawWireSphere(bounds.center, Mathf.Max(Mathf.Max(bounds.extents.x, bounds.extents.y), bounds.extents.z));
}
}
if (this.ShowCenter)
{
Gizmos.DrawLine(new Vector3(bounds.min.x, bounds.center.y, bounds.center.z), new Vector3(bounds.max.x, bounds.center.y, bounds.center.z));
Gizmos.DrawLine(new Vector3(bounds.center.x, bounds.min.y, bounds.center.z), new Vector3(bounds.center.x, bounds.max.y, bounds.center.z));
Gizmos.DrawLine(new Vector3(bounds.center.x, bounds.center.y, bounds.min.z), new Vector3(bounds.center.x, bounds.center.y, bounds.max.z));
}
Handles.BeginGUI();
var view = SceneView.currentDrawingSceneView;
var pos = view.camera.WorldToScreenPoint(bounds.center);
var size = GUI.skin.label.CalcSize(new GUIContent(bounds.ToString()));
GUI.Label(new Rect(pos.x - (size.x / 2), -pos.y + view.position.height + 4, size.x, size.y), bounds.ToString());
Handles.EndGUI();
}
}
And also the code for the GetBoundsWithChildren method.
/// <summary>
/// Gets the rendering bounds of the transform.
/// </summary>
/// <param name="transform">The game object to get the bounding box for.</param>
/// <param name="pBound">The bounding box reference that will </param>
/// <param name="encapsulate">Used to determine if the first bounding box to be calculated should be encapsulated into the <see cref="pBound"/> argument.</param>
/// <returns>Returns true if at least one bounding box was calculated.</returns>
public static bool GetBoundWithChildren(Transform transform, ref Bounds pBound, ref bool encapsulate)
{
var bound = new Bounds();
var didOne = false;
// get 'this' bound
if (transform.gameObject.renderer != null)
{
bound = transform.gameObject.renderer.bounds;
if (encapsulate)
{
pBound.Encapsulate(bound.min);
pBound.Encapsulate(bound.max);
}
else
{
pBound.min = bound.min;
pBound.max = bound.max;
encapsulate = true;
}
didOne = true;
}
// union with bound(s) of any/all children
foreach (Transform child in transform)
{
if (GetBoundWithChildren(child, ref pBound, ref encapsulate))
{
didOne = true;
}
}
return didOne;
}
415dc9a7-173b-462a-9054-d503c9fcf860|0|.0
I created the xDocs page July 11, 2008 and I am only now realizing that I had never provided an actual download to the control. I r phail saucie QQ Jebus I’m bad for doing that! I can’t believe how much stuff I have started on this site only to have it never completed.
cc36041c-ab6f-4bcb-a0b8-86b9433c22b9|0|.0
|
|