Encapsulating Alpha Fade in Unity3d

November 12, 2010 – 21:09

Several days into my late Unity3d project I realised that the was a bulk of code designed solely to make an object invisible by fading it out of the scene. The code was not complex although because of the way it was all in one class it appeared complex.

After doing some research into the best way to go about making this change, realised it was both convenient and logical to extract the code into a separate script and attaching that to the object that I wished to apply the effect to.

This meant that instead of nested if-statements for state management in a script attached to the Main Camera I was able to make declarative statements:

GameObject.Find(“TargetObject”).GetComponent<SmoothAlpha>().MakeVisible();

I have named the script SmoothAlpha only by my convention no actual smoothing or damping of the alpha value, it is simply a linear reduction of the materials alpha value.

There are many improvements that could be made to the script, some of which I may well do over the coming weeks:

  • Should include a delegate call back to signal when the fade is complete.
  • Should include methods to instantly make an object (in)visible.
  • Should support changing the alpha of child GameObjects in unison with the parent.

In have included the full script below the cut.

Unity3d plus three weeks

November 6, 2010 – 2:07

It is about 3 weeks on since I started learning Unity3d, and today Makemedia delivered the product we were working on using it. I have thoroughly enjoyed the process and the experience, there is still much to learn however I am much more confident experimenting with Unity3d to see what I can come up with.

As I am not going out to see the fireworks tonight, I put together a 3d scene to demonstrate some of Unity Basics particle effects in the form of a personal fireworks display.

Move around in the scene using W, A, S, D or the Arrow Keys you can move your head by moving the mouse.

Some of the rockets go a bit crazy some time and fire off into the distance at low speeds which is quite peculiar when it is towards the camera.

Source Code

Unity 3D

October 16, 2010 – 21:18

I am starting a project next week using Unity3D, I have known about this for a while and have poked around a bit to try and figure out how to do various things. I have been really impressed as to how fast you can get something done with what is basically a free product.

There are some superb videos on Unity3d Student which have been invaluable. I think I have got my head around the controls, UI, paradigms and scripting, although not all in one scene. As evidence of my work I have made three balls bounce around the screen, something akin to a carpenter making a door stop perhaps, but I am sure I will learn.

Changing code accessibility modifiers quickly

October 12, 2010 – 21:20

I have two hints today both of them involving changing accessibility modifiers. The first is a feature of CodeRush that I accidentally discovered while testing out the Visual Studio 2010 Productivity Power Tools the second is a great new feature of Visual Studio 2010.

For those who don’t know what I mean by accessibility modifiers, those are the keywords you put before blocks of code that define how that code can be accessed, this is all enforced by the compiler giving you nice compiler error messages if you violate these rules. To provide an example the following auto-properties are all have the accessibility modifier “public”:

[Column] public string Name { get; set; }
[Column] public string Description { get; set; }
[Column] public decimal Price { get; set; }
[Column] public string Category { get; set; }

CodeRush gives you a handy way to change the User interface by clicking the icon to the left of the code block, you then get a set of actions you can perform upon the that block of code.

Code Rush Code Context Menu

As with most everything in CodeRush you can access this functionality from the keyboard anywhere within the scope of that code block by pressing Alt + Up or Alt + Down to cycle through the five possibilities:

  • public
  • internal
  • protected internal
  • protected
  • private

This means that if you need to change access modifiers, either to tighten up or relax the access points into your code you can do it by pressing a hand full of keys (between two and six to be exact), much faster than navigating to the top of the method highlighting and replacing the keyword.

My second hint is something that I have been using quite regularly, lets take the above example again:

[Column] public string Name { get; set; }
[Column] public string Description { get; set; }
[Column] public decimal Price { get; set; }
[Column] public string Category { get; set; }

I want to change all four fields to “be internal”, I could go in and change each one manually or better still use the above keyboard shortcuts (Alt + Down, Down, Alt + Down, etc.) the faster alternative would be to hold down the Alt key then select from the first character of the first “public” to the last character of the last “public” keyword.

While holding down Alt traditional selection behaviour is not followed and only the “public” keywords are selected on all four lines:

VS2010 Line Select

You can then type your new visibility modifier overwriting the selected components of all four lines in one fell swoop:

[Column] internal string Name { get; set; }
[Column] internal string Description { get; set; }
[Column] internal decimal Price { get; set; }
[Column] internal string Category { get; set; }

I think that is neat!

Elevated Command Prompt

October 7, 2010 – 13:32

I explained how to get an elevated Command Prompt to perform system tasks in the comments of my post about setting the MTU in Windows 7, I am writing the up a bit clearer and linking it from that post.

In Vista and Windows 7 applications don’t automatically get administrator privilege, they either need to request it or the user needs to explicitly start the application as an Administrator. The way to do this with the Command Prompt is as follows:

  1. Press the “Start” button.
  2. Type “Command”.
  3. “Command Prompt” will be shown in the search results.
  4. Right Click “Command Prompt” and select “Run as Administrator” (it will have a blue and yellow shield beside it).
  5. When prompted click “Yes” to allow Command Prompt to start as Administrator.
  6. You will know it has worked because the title bar will start with “Administrator:”

Finding Code Issues

October 1, 2010 – 22:02

As programmers we are well known for writing bug free perfectly formed code first time round, as such I don’t really understand why DevExpress implemented the code issues feature… no wait… that should be the other way round.

CodeRush has several ways to access the Code Issues user interface, first off there is the thin file overview down the right hand side of the viewport. In the code itself there are handy contextual hints too.

Code Rush Issue In Context

In this example, “this.” is redundant and has been greyed out, if you hover over it it will tell you more about the issue and how to resolve it. Different issues have different notation so code that is to be transformed will have a coloured underline.

In the process of going though a file created by someone else the code style was a bit off – I was able to quickly bring it in line with the project preferences by using the shortcut keys Alt + PageDown to skip between the issues then Ctrl + ‘ to fix the issues quickly.

Great feature for spotting mistakes as you code, and also for learning new language features as they are introduced into the specification.

Spot The Mistake 1

August 21, 2010 – 18:30

This one had me puzzled for about an hour, I shall endeavour to post the answer in the comments in short order.

foreach (var id in CharacterIdentities)
{
  QueryMethodAsync(
    APIMethods.CharacterSkillInTraining,
    m_userId,
    m_apiKey,
    id.CharacterID,
    (x) =&gt; OnSkillInTrainingUpdated(x, id));
}

Using EVEMon Data with LINQPad

July 31, 2010 – 22:52

LINQPad is an awesome aide to .NET Developers. Written by Joseph Albahari of LinqBridge and the C# In a Nutshell series fame. LINQPad allows the developer to write, compile and run C# or VB.NET Expressions, Statements of Programs outside of Visual Studio.

Everything I am going to show you in this post can be done with Visual Studio simply by wrapping the text in a new console application, and adding references to the DLLs. However I strongly encourage you to download LINQPad and give it a go.

In the event you are using 64-bit windows and are still using LINQPad 2 you will need to download the x86 version of LINQPad 2, as all of the EVEMon assemblies are compiled for x86. If you have LINQPad 4 you don’t need to worry about.

Assuming you have EVEMon installed, the first step is to load the EVEMon.Common.dll assembly into LINQPad:

  1. Go ahead and fire up LINQPad ensure you have a new query window open
  2. Press F4 (Query -> Query Properties).
  3. Click the “Browse…” button at the bottom of the properties window.
  4. Navigate to the EVEMon install directory.
  5. Select “EVEMon.Common.dll”

While you have “Query Properties” open go to the “Additional Namespace Import” tab and add the following two lines:

EVEMon.Common.Data
EVEMon.Common

EVEMon.Common was designed to work as part of a long running process, namely the EVEMon application sitting in your system tray from when you turn your computer on until you turn it off, as such we need load the static data from the data files.

EveClient.Initialize();

Now we get to do some LINQ,

var allItems = from item in StaticItems.AllItems
	       where item.Family == ItemFamily.Ship
	       select new
	       {
	           item.Name,
	           item.Race,
	           CPU = item.Properties[DBConstants.CPUOutputPropertyID].Value.Value,
	           PG = item.Properties[DBConstants.PGOutputPropertyID].Value.Value,
	           item.Description
	       };

I could start to explain the above line by line, but there are lots of really good LINQ articles on the Internet, including one by Joseph Albahari. We will just say that the above pulls all of the ships out of EVEMon’s Items data file and selects the Name, Race, CPU, PowerGrid and Description property for each one.

Now we see my favorite aspect of LINQPad, the .Dump() extension method, simply running the following command:

allItems.Dump();

Will output the data we have just queried as a nice HTML Table:

That is all I have for you for now, I am working on a project that uses this data outside of EVEMon, keep an eye on Twitter where I will hopefully be providing a link for testing in the not too far distant future.

Tracing A Method Signature

July 16, 2010 – 22:03

Over the past three weeks I have discovered that many performance problems with Windows Forms applications are down to certain events being fired very rapidly, usually these are down to layout operations being triggered by updates to controls.

Without the use of RedGate Software’s excellent performance profiler I have been forced back into the habit of temporarily peppering the code I suspect of being a problem with trace messages.

For a while I was quite disorganised using trace messages such as “Entered SoAndSoMethod”, “OnSomeEvent Triggered”, etc. Over time I have settled into using the declaring class and method name to identify which method was being called.

Thinking about it today I decided this was still too much work (yeah, I am that lazy), I wondered if System.Reflection could help me:

public static void Trace()
{
    var stackTrace = new StackTrace();
    var frame = stackTrace.GetFrame(1);
    var method = frame.GetMethod();
    var parameters = FormatParameters(method.GetParameters());
    var declaringType = method.DeclaringType.ToString().Replace("EVEMon.", String.Empty);
 
    Trace("{0}.{1}({2})", declaringType, method.Name, parameters);
}
private static string FormatParameters(ParameterInfo[] parameters)
{
    var paramDetail = new StringBuilder();
 
    foreach (var param in parameters)
    {
        if (paramDetail.Length != 0)
            paramDetail.Append(", ");
 
        paramDetail.AppendFormat("{0} {1}", param.GetType().Name, param.Name);
    }
 
    return paramDetail.ToString();
}

This means that with liberal application of:

EveClient.Trace();

Will output the following to the trace:

0d 0h 00m 03s > CharacterMonitor.OnLoad(ParameterInfo e)
0d 0h 00m 03s > CharacterMonitor.multiPanel_SelectionChange(ParameterInfo sender, ParameterInfo e)
0d 0h 00m 03s > CharacterMonitor.multiPanel_SelectionChange(ParameterInfo sender, ParameterInfo e)

Hopefully that will save a few seconds here and there. It is a shame that reflection can’t get the actual values of the parameters from the frame, as that would be even more useful.

ASP.net 3.5 GridView RowCommand event fired twice

April 1, 2010 – 16:25

I am writing this up to hopefully save someone else time in the future, this particular problem took up six hours of my day yesterday causing quite a bit of frustration for me, as the developer, and the users of the application.

If you are searching for the solution scroll down to the bottom of the page where I will outline the solution I used to resolve the problem. It is also worth pointing out that this does appear to be fixed in .NET 4. Certainly I was able to consistently reproduce the problem with VS2008/.NET 3.5 on multiple different computers. However after converting the project to VS2010/.NET 5 I haven’t seen the issue.

Explanation of the problem

I wrote and maintain an application that publishes a list of courses and allows users to book onto these courses, what I have listed below is a simplified version of this application.

The administration console contains two lists:

  • Published Courses – courses visible to all employees.
  • Unpublished Courses - courses waiting to be published, only visible from the administration console.

Courses can be freely published (i.e. moved from Unpublished to Published) by clicking green tick. Courses that have not had any bookings made can be unpublished by clicking the red cross.

The cross and the tick are implemented as GridView ButtonFields:


<asp:ButtonField ButtonType="Image" CommandName="UnpublishCourse"
    ImageUrl="~/images/unpublish.png" InsertVisible="False" Text="Unpublish" />

This application has been running for six months, the issue had not been observed up until yesterday. The user explained to me that when they were publishing courses they were always published in pairs, equally when unpublishing courses it was being done in pairs, concealingly unpublishing a course with bookings.

Investigating the problem

Initially I tried to reproduce this on my local machine, backed up and subsequently restored the database locally made sure I was running the same revision as the server and fired it up. Couldn’t reproduce the problem, no matter how fast I clicked it wouldn’t happen. Tried various permutations of code and database but could only reproduce on the server.

Refreshed the binaries on the server with the HEAD from subversion, problem was still happening most of the time. I confirmed that it wasn’t an issue with the stored procedures by running them manually through LinqPad.

I started putting debug statements at the entry points to the critical parts of the code, this yielded an interesting output on my development machine, each time the cross or the tick was clicked UnpublishedGridView_RowCommand was fired twice. This gave me something to search for, seems I am not the only one to have this problem, Microsoft tried to reproduce it in 2006 but couldn’t.

Solving the problem

As it turns out there are several ways of fixing the problem, several people have used timers to “debounce” the RowCommand event, assuming that the event is always going to be fired twice a session variable can be used to filter out the second event.

Because the event is only fired twice when ButtonType=”Image” not when ButtonType=”Link” you can set the text property to the HTML to render your image. This resulted in the code above becomming:


<asp:ButtonField ButtonType="Link" CommandName="UnpublishCourse"
    InsertVisible="False" Text="<img src=images/unpublish.png />" />

This proved to be the simplest possible solution, Visual Studio 2008 throws a warning about ASP.net validation, but I can live with that as long as the application works. In addition to the simplicity of the solution it also continues to work in ASP.net 4 (which doesn’t exhibit the double event behaviour).