Braindrop Labs Apps

Category Archives: Quick Tips

How to Fix a Blurry Android App Icon in Unity

First thing is first, I did not come up with the solution. All the credit goes fully to TheDreamMaster over on the Unity Answers Forum. The issue lies in the fact that Unity automatically optimizes your textures by converting their dimension to a power of two – which often leads to blurry app icons. What TheDreamMaster discovered is that you need to explicitly set the Texture Type to GUI (Editor\Legacy) for each app icon. You can simply select all your app icons at once in the Project View and then in the Inspector change the previously mentioned Texture Type setting. Boom done.

How to Dynamically Load Scripts and StyleSheets using jQuery

Though not necessarily common, there are times when you want to conditionally load CSS stylesheets and/or JavaScript files (or modules) on a webpage. An example of where this personally came in handy was for a video module I developed which was responsible for managing video playback, playlist functionality, and the popup HTML that serves as the video container. The module was designed to be utilized in two distinct ways on the website.

  1. Minified – on an “all things video” page
  2. Standalone – on any page of the website that needed to playback video


Since not all pages on the website needed to playback video, the decision to load the module and its required assets (css, other javascript, and a web font) on every page would be irresponsible. This fact led me down the path to find out how to dynamically load javascript and dynamically load css. As you can see there are many people who have looked for a solution to this problem in addition to many solutions for it. In our specific case jQuery was loaded on every page and thus could be utilized (Note: jQuery is not required to achieve this but is helpful for the sake of brevity if already loaded). I took advantage of this fact to keep the solution very simple and succinct. You can view an example below:

//conditional determining the need to load a stylesheet or javascript file

var css = "path/to/file.css";
document.createStyleSheet ? document.createStyleSheet(css) : $("head").append("<link href='" + css + "' rel='stylesheet' type='text/css'>");

//you can similarly inject a <script> into the <head> element or preferably make an AJAX call for a script

If you are unfamiliar with the ternary operator (used on line 4) it is a shorthand for an if/else conditional. I utilize this to succinctly determine if the document contains the createStyleSheet method (thanks Internet Explorer) and then in a browser agnostic way inject the stylesheet into the document to be loaded by the browser. That’s all there is to it.

Removing Padding

Recently I ran into an issue with AlertDialog.Builder in Android when I was creating custom AlertDialog instances. In the Android docs for AlertDialog it states that there is this public method signature:

setView (View view, int viewSpacingLeft, int viewSpacingTop, int viewSpacingRight, int viewSpacingBottom)()

I thought, “Cool, this is just what I need”.

Unfortunately after trying to make the same setView call from AlertDialog.Builder, I learned that its signature did not have the option to pass in the spacing arguments. Upon some research on the Google machine and at StackOverflow (How to change dialog background color programatically? & custom alert dialog getting unwanted padding), I found that others had similar issues.

After further investigation on StackOverflow I found the answer I was looking for via this link (Remove padding around alert dialog). So in essence, when using AlertDialog.Builder to create custom AlertDialog instances, you need to instantiate an actual Dialog or AlertDialog instance prior to making the desired setView call.

Here is an example (from the app Noded which will be released Q1 2014) highlighting the before and after:

Before

	@Override
	protected Dialog onCreateDialog(int pId)
	{
		if(pId == ViewManager.DIALOG_ID_KEY)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setView(ViewManager.getInstance().getKeyDialogView());
			return builder.create();
		}

		return null;
	}

After

	@Override
	protected Dialog onCreateDialog(int pId)
	{
		if(pId == ViewManager.DIALOG_ID_KEY)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			AlertDialog dialog = builder.create();
			dialog.setView(ViewManager.getInstance().getKeyDialogView(), 0, 0, 0, 0);
			return dialog;
		}

		return null;
	}

Before (Left) and After (Right) – Notice the sliver of black color at the top and bottom of the dialog.

Example Code

If you write for loops like this:

for(var i = 0; i < myList.length; i++)
{
	//loop me up Scotty
}

You should instead write them like this:

var len = myList.length;
for(var i = 0; i < len; i++)
{
	//loop me up Scotty
}

Or better yet, like this:

for(var i = 0, len = myList.length; i < len; i++)
{
	//loop me up Scotty
}

Reasoning – Smarter

Though the examples above are in JavaScript, the fundamental idea is applicable in many (if not all) languages. The small optimization between the first example and the second is to simply cache the value that gets evaluated in the condition expression of the for loop. It may come as a good reminder that in the anatomy of a for loop, the condition is evaluated before each loop iteration. By caching the value that gets compared against the counter value, you get an optimization win for each iteration. This optimization win may be tiny and in some cases negligible, but ultimately I believe it is the right and better thing to do.


Reasoning – Cleaner

Some developers may argue against and/or simply not like creating a new local variable just to cache the value being compared in each loop iteration. To those developers, I provided you the third code example above. In this example, the cached value is “inlined” into the initialization expression of the for loop. Now you get the best of both worlds. #Winning

Windows Shortcuts to Quickly Create New Text Files and Folders

I often want to quickly create new text file or folder when I’m working on my machine. Usually, it takes me just a little bit longer than I feel it should (right click for the context menu > navigate to ‘New’ > navigate to the item I want). Until today I didn’t believe Windows provided a quicker way to automatically create a new text document or folder. Though I still think it could be improved, here are some of the handy shortcuts:

  • New Text File – Right click + w + t
  • New Folder – Right click + w + f
  • *New Shortcut – Right click + w + s
  • *New Photoshop Document – Right click + w + a


* I have PS installed, so depending on the applications you have installed you’ll probably have other shortcuts than I do. Just try them all and see what you have. I’m not gonna spend the time right now, but I’m sure you could customize this within Windows (probably not as easy as it should be however). #WindowsLegacyCode

How to Change Text Selection Color with CSS

I recently came across a new (to me) CSS3 selector that enables you to change the highlight background color and/or text color of selected text. Technically, it can be used for any DOM element that is selected, but text will be the most common. It is extremely easy to implement and by using the * selector for selecting all elements you can quickly have your entire site update with your desired selection colors. Here is the sample that is used on this site currently:

*::selection
{
	background: #000;
	color: #fff;
}

*::-moz-selection
{
	background: #000;
	color: #fff;
}

As of the time of this writing vendor prefixes are still necessary, but hopefully that changes soon. You can reference w3schools to dig a bit deeper. Chrome, Firefox, Safari, and IE9+ can utilize this selector.

Delegation Design Pattern: What and Why

Delegation is a programming design pattern where “…a helper object, known as a delegate, is given the responsibility to execute a task for the delegator“. This definition excerpt comes from the Delegation Pattern Wikipedia page if you’d like to dig deeper.

What the above definition doesn’t tell you is that there can be many delegators. This fact is what makes this pattern useful. At the core, you can have a single object (or set of code) that acts on the behalf of many objects – more bang for your buck. Say you have 20 buttons inside a container object and you want to set up click/tap event listeners for each button. Using event delegation, you can instead set up an event listener on the container as opposed to each button instance. This can lead to better code organization as well as code efficiency if used correctly. In the context of events, delegation is super helpful for these exact reasons.



Event Delegation

I’m used to event delegation in AS3 and JavaScript where this pattern is most commonly achieved through the use of event bubbling. I however prefer implementing event delegation by piggybacking Signals (AS3 Signals / JS Signals). Signals piggybacks the powerful observer pattern (#doublepiggyback) and it gives me maximum flexibility while encouraging loose coupling.

I’ve been digging into how the Unity community achieves event delegation, and I haven’t had much luck… until recently. I posted this question to the 2D Toolkit forums and shortly after doing so a lightbulb went off and I posted my solution. Shortly after posting my solution unikronsoftware (forum admin) responded with an example of how to achieve this via an event bubbling style approach. Had I not come across my own solution just prior, I would most likely be planning out how best to implement his suggestion. Though his solution is still a good one, I feel my solution is magnitudes lighter, cleaner, and easier to implement.


The Solution – Core Listener

//multiple hit check example
private void onEventDelegationClick(tk2dUIItem pUIItem)
{
	Vector2 pos2d = pUIItem.Touch.position;
	Ray ray = Camera.main.ScreenPointToRay(new Vector3(pos2d.x, pos2d.y, -1));
	RaycastHit[] hits = Physics.RaycastAll(ray);

    for(int i = 0; i < hits.Length; i++)
    {
    	Debug.Log(hits[i].collider.gameObject.name);
    }
}

//single hit check example
private void onEventDelegationClick(tk2dUIItem pUIItem)
{
	Vector2 pos2d = pUIItem.Touch.position;
	Ray ray = Camera.main.ScreenPointToRay(new Vector3(pos2d.x, pos2d.y, -1)); //-z is z-depth of my UI
	RaycastHit hit;
	Physics.Raycast(ray, out hit);

	//UI level button example ("Button1", "Button2", etc as GameObject name)
	string hitObjectName = hit.collider.gameObject.name;
	int levelNum = int.Parse(hitObjectName.Replace("Button", ""));
	Signals.LoadLevelRequest(levelNum);
}

…and the code breakdown:

  1. Get a 2D touch point
  2. Create a ray using this 2D touch point
  3. Cast the ray from the camera into the 3D scene in an effort to see what it hits
  4. The cast returns hit(s) in the form of a RaycastHit object or collection of RaycastHit objects
  5. Parse the hit(s) however you desire (for the single hit example above I preview a way to load levels)


The Solution – Core Delegator

Where event delegation comes into play is on line 25 in the example above. I make a call through my Event Manager which I call Signals.cs. In essence Signals is just a script which is attached to an empty game object in my scene. What makes this script special is that it has an Event API Chunk for each custom event type in my game/application. As a result of the way each chunk is set up, it becomes trivial to have game-wide or application-wide communication. In order to achieve this communication I utilize a C# delegate, a built in event object, and a public static method. Combined they comprise a single Event API Chunk. Here is an example:

...

	//load level request
	public delegate void LoadLevelRequestHandler(int pLevelToLoad);
	public static event LoadLevelRequestHandler onLoadLevelRequest;
	public static void LoadLevelRequest(int pLevelToLoad){ if(onLoadLevelRequest != null) onLoadLevelRequest(pLevelToLoad); }

...

With these Event API Chunks in place they can be combined with methods like the onEventDelegationClick() examples to achieve efficient, flexible, and light application-wide communication. For the example given I could have numerous listeners (say a GUIManager, a DataManager, and a LoadManager) all execute their own functionality based off this single event extremely easily. Though this particular example is dependent on user interaction, you can obviously use this same approach for custom events not initiated by user input. This is extremely powerful and has been the best approach I’ve come to know in Unity. I hope this is helpful, but if you know a better approach or have an idea for improvement, I’m all ears.

Extending the Editor

If you use Unity and are currently unfamiliar with Editor Windows or Extending the Editor in general you have some reading to do and then some watching to do. Long story short, you can create your own custom windows and scripts that run in Editor Mode as opposed to the traditional Play Mode. They are insanely useful and can help streamline all kinds of workflows or add functionality you wouldn’t have otherwise. Here’s a simple example that I created enabling me to quickly save level files while in Edit Mode or Play Mode:

Unity Custom Save Editor Window

Custom Save Editor Window

I’ve recently delved into creating my own custom Editor Windows in Unity to help with productivity. In one instance, I wanted to be able to rearrange GameObjects in my Scene View (not depending on being in Play Mode) and then save metadata involving each object to a file. Then during runtime I could reconstruct the scene layout without needing to actually load a new scene. Basically, I use a PoolManager and simply update the layout/state of my pooled GameObjects as opposed to loading an entire new scene. To accomplish what I was after, I created a custom Editor Window (pictured above) that enabled me to simply enter a World and Level id set followed by a Save button. I can now easily arrange my scene layout and save it and metadata to disk. This data can then be loaded and utilized to recreate a prerecorded scene by simply loading a small binary file during runtime – :) fast and light.

Refresh Project Assets when Using a Custom Editor Window

I got this working and it has since sped up my level creation time tremendously. One thing however that was beginning to bother me was that after I had saved different level layouts, I’d have to select the project folder that contained my newly saved files and manually refresh it for Play Mode to recognize the newly added files. Upon some digging I discovered this gem:


AssetDatabase.Refresh();

So now after I click my custom save button, I make this call, and Unity’s Project Panel automatically refreshes resulting in my newly added file to be recognized instantly. This is a super simple but handy one liner that will help you in many situations when updating your project assets while in Edit Mode.