How to nicely select item in the Unity’s two-column Project Browser

Hey, I’ll try to be short.
I’m working on the Maintainer‘s Issues Finder improvements and one of such improvement was to select (show) the scene file at the Project Browser along with target GameObject in the Hierarchy when user press “Show” next to the found issue.

At the first iteration, I did the selection using Selection.objects and it worked great with One-column view mode of the Project Browser.
But things get weird when I switched to the two-column mode: target scene file still get selected, but it didn’t show up until I manually navigated to the folder with that file.

And surprisingly, I faced two common issues here:
1. Unity has no API to let you know in which mode the Project Browser is.
2. Unity has no API to select specific folder in the first column of the Project Browser.

But thankfully, we have ILSpy and reflection! 😉
So, using ILSpy I managed to find all what I need;
UnityEditor.ProjectBrowser class
– static s_LastInteractedProjectBrowser field to access last used ProjectBrowser window (we can have lot of ProjectBrowsers in Unity layout).
– private field m_ViewMode of the ViewMode enum type which has two values – OneColumn (0) and TwoColumns(1)
– private ShowFolderContents() method which expands first column of the TreeView to the specified folder and selects it

And here is a resulting code which selects both object in scene hierarchy and scene file in Project Browser in any column mode (one or two columns):

public void SelectObjectAndScene(GameObject targetGameObjectInScene, string scenePath)
{
	List<Object> selection = new List<Object>();

	Object sceneFile = AssetDatabase.LoadAssetAtPath(scenePath, typeof(Object));
	selection.Add(sceneFile);

	Type projectBrowserType = Type.GetType("UnityEditor.ProjectBrowser,UnityEditor");
	if (projectBrowserType != null)
	{
		FieldInfo lastProjectBrowser = projectBrowserType.GetField("s_LastInteractedProjectBrowser", BindingFlags.Static | BindingFlags.Public);
		if (lastProjectBrowser != null)
		{
			object lastProjectBrowserInstance = lastProjectBrowser.GetValue(null);
			FieldInfo projectBrowserViewMode = projectBrowserType.GetField("m_ViewMode", BindingFlags.Instance | BindingFlags.NonPublic);
			if (projectBrowserViewMode != null)
			{
				// 0 - one column, 1 - two column
				int viewMode = (int)projectBrowserViewMode.GetValue(lastProjectBrowserInstance);
				if (viewMode == 1)
				{
					
					MethodInfo showFolderContents = projectBrowserType.GetMethod("ShowFolderContents", BindingFlags.NonPublic | BindingFlags.Instance);
					if (showFolderContents != null)
					{
						Object sceneFolder = AssetDatabase.LoadAssetAtPath(Path.GetDirectoryName(scenePath), typeof(Object));
						showFolderContents.Invoke(lastProjectBrowserInstance, new object[] { sceneFolder.GetInstanceID(),  true});
					}
					else
					{
						Debug.LogError("Can't find ShowFolderContents method!");
					}
				}
			}
			else
			{
				Debug.LogError("Can't find m_ViewMode field!");
			}
		}
		else
		{
			Debug.LogError("Can't find s_LastInteractedProjectBrowser field!");
		}
	}
	else
	{
		Debug.LogError("Can't find UnityEditor.ProjectBrowser type!");
	}

	selection.Add(targetGameObjectInScene);
	Selection.objects = selection.ToArray();
}

This code might be not elegant and clean since it’s a quick try to leave snippet in the blog. Feel free to correct my where I’m wrong.

P.S.: if you wish only show some file in the Project Browser without selection, just use EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(scenePath, typeof(Object))); It will work fine with one-column layout and will work with two-column layout if you don’t select anything else.

Found a typo? Please, highlight it and press Shift + Enter or click here to inform me!

Share Button

Update on my Unity3D plugins

Hey there, dear friends, subscribers and strangers passing by!
Today I’d like to tell you something about my Unity3D plugins I sell on the Unity Asset Store.

Let me begin with one plugin I didn’t introduced on my blog yet: Advanced FPS Counter!

This is a super simple and flexible way to show FPS, memory usage and some hardware info right in your app on target platform \ device.
This plugin may be really useful on the project testing phase, when you send your app to the beta testers and wish to hear from them what performance on what hardware do they have. Or if you just wish to see all these data yourself in your app running on the target device.
Anyway, I hope you’ll find it useful and helpful. And most important part – it’s almost free, currently I sell it for just five bucks (except the Nebraska)!

Another good news I’d like to tell you – latest Anti-Cheat Toolkit update finally hit Asset Store and now available for purchase!

It brings some great new features, like speed hack detection and I did fixed lot of community reported bugs and implemented some community requested features.
I also wish to let you know I’m already working on next significant update which will raise plugin’s price a bit. As you may see Anti-Cheat Toolkit went really far from what it was on its first Asset Store day, and I never changed its price since releasing it in Aug’13. I hope you see it deserves few additional bucks =)
So, I’d suggest to hurry and grab it for current low price until next update released! =P

After all, I wish to hug all people helping me to make my plugins better or supporting me in any other way. In first place I’m talking about all my friends and customers who were so kind to send me a bug report, or leave a review in Asset Store or just say me “good work” on forums. Thank you all, guys!

Special thanks and hugs fly out to my little-almost-year princess and my wife, her great mommy <3!

Found a typo? Please, highlight it and press Shift + Enter or click here to inform me!

Share Button

Types conversion in Unity3D

Hey there!
Recently I needed to store floats as integers and vice versa (used it to easily xor floats in my Anti-Cheat Toolkit) and I came across few ways of doing this.

Unsafe pointers – fastest one:

public unsafe int FloatToInt(float value)
{
	return *(int*)&value;
}

public unsafe float IntToFloat(int value)
{
	return *(float*)&value;
}

Easy, right?
Please, note, it requires /unsafe compiler option. To leverage unsafe operations in unity, you have two commonly used options to choose from:
1. Use it in a separate dll, compiled with /unsafe option.
2. Set /unsafe option right in your project using “Global Custom Defines”, putting it in .rsp file in your Assets/ root. See bottom of this page for details.
And keep in mind unsafe code is not supported in some build targets, like Web Player and Flash Player.

Unions (Explicitly layouted structs) – slower than pointers, but works in Web Player (not in Flash Player, d’oh!):

[StructLayout(LayoutKind.Explicit)]
internal struct FloatIntUnion
{
	[FieldOffset(0)]
	public float f;

	[FieldOffset(0)]
	public int i;
}

public int FloatToInt(float value)
{
	var u = new FloatIntUnion();
	u.f = value;
	return u.i;
}

public float IntToFloat(int value)
{
	var u = new FloatIntUnion();
	u.i = value;
	return u.f;
}

Pretty easy to use, safe and works on more build targets comparing to pointers.
Note [StructLayout(LayoutKind.Explicit)] attribute is used here in conjunction with [FieldOffset(*)] attribute. It allows you to set each struct field position in memory explicitly and read data stored there.

BitConverter class – pretend to be slowest:

public int FloatToInt(float value)
{
	return BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
}

public float IntToFloat(int value)
{
	return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
}

Safest one though (works even in Flash Player).

I should mention there are so-called “safe pointers” in C#, used through Marshal class, but they are pretty complicated, require unmanaged memory allocations and constant control on memory at all (C# developers are usually rely on GC and do not bother on allocations), so I’ll not post Marshal review here for now, these 3 methods I described are usually enough for the types conversion.
I hop I’ll have some time to make performance tests on these methods in latest Unity 4.3 later and post results with tests sourcers here (in another blog post).

Questions? Ask in comments!

Found a typo? Please, highlight it and press Shift + Enter or click here to inform me!

Share Button

Unity3D threads – measuring performance

Hey everybody!
Sometimes people ask me about delayed actions or threading in Unity3D and usually I suggest to use coroutines since they are suitable for the most cases I faced with.
But sometimes we need to use true threading and make some calculations faster, A* path finding for example.
So I decided to make a fast-written performance comparison of traditional code execution vs. threaded version. I searched for some simple threads managers and found this really simple Loom class from whydoidoit accidentally.

I did a simple test app for different platforms (I attached archive with apps and sources at the end of this post) and found some results pretty interesting.
All my code is trying to do – is just to make CPU think a little while working with huge array of Vector3D instances (10 000 000 for Desktop platforms and 1 000 000 for mobile platforms):

private void Run()
{
	const float scale = 432.654f;

	for (int j = 0; j &lt; arrayLength; j++)
	{
		Vector3 v = vertices[j];

		v = Vector3.Lerp(v * scale / 123f * v.magnitude, v / scale * 0.0123f * v.magnitude, v.magnitude);

		vertices[j] = v;
	}
}

This is a simple dummy code as you can see.
I added simple Ant model (hello, Away3D examples authors! :)) with rotation at Update() to the scene in order to see how app can freeze while running this ugly code in main thread.

JTMLjQ0

I did few tests of this code as I mentioned previously, both in sync (straight execution in main thread) and async (running it the separate threads) modes, here are results I’ve got (S – sync, A – async):
Continue reading

Found a typo? Please, highlight it and press Shift + Enter or click here to inform me!

Share Button

AIR vs. Unity3D. Who’s faster? (Update 1)

Update 1: uploaded some sources (look at the end of article).

Hey there!
Yeah, it’s been a while blahblahblah.. To the point! =)

Sometimes I’ll highlight actual files from the archive, attached at the page bottom.

Sometimes I see Flash developers interested in the Unity3D lately, and I – one of them actually)
I work with Unity for a while already and all I can say – it’s fantastic experience! So cool to learn C# language (I hope other Flash devs make wise decision to code in C# as well), to learn new community and people, to meet a lot of new challenges and to look at 3D world from a new point at all!

Many Flash developers are still uncertain they should try Unity and spend their time learning this brand new world though.. And in some cases it’s built on top of the AIR and Unity3D performance differences obscurity. So I’ll unveil portion of this differences in this article to help those Flash developers make a choice (whatever what they choose)!

All examples I’ll compile with AIR 3.6 and Unity3D 4.1 and I’ll try to keep similar functionality and look of these examples to let them compete.
I’ll test builds on the pretty slow Samsung Galaxy Tab 10.1 and make some tests on the desktop as well.

Intro

Okay, let’s start from comparing empty builds.
To measure FPS in unity3D I’ll use hand-made FPSmeter working with GUIText.
In AIR builds I’ll use different FPSmeters, usually in-built to the frameworks I’ll use.
Well, let’s see to the built apks (I built Captive Runtime in AIR and usual release build in Unity3D):
Continue reading

Found a typo? Please, highlight it and press Shift + Enter or click here to inform me!

Share Button