Category Archives: C#

Renaming c# classes and Unity…

As far as I know, there is no ‘correct’ way to rename a class that you’ve built inside a Unity C# file with ease and 0 pain…  but there is certainly a wrong way to do it:

Approach it in this order:

Rename the ????.cs file using the Unity Editor.  Click on the file in the project explorer and use what ever method you’d like to rename it to the new class name.  This means that Unity will keep a reference to the newly named file and any instances of that class file attached to objects in the scene will get updated.

Now, open the file in your text editor (Mono, VS, whatever) and use ‘Refactor or Rename’ on the actual class name and let the editor change all references in the project.  Save all the changed files and you should be able to build just fine.

Go back to Unity and the project should build and run without any errors.

If you do what I did – rename the class first in your text editor, then you’ll end up replacing every ‘missing script’ error by hand – not so much fun — you’ve been warned!

Sorted Hashtable Keys

By default, a hashtable does not keep a sorted list of keys, but sometimes it’s useful to do so.

In order to do this in one line with linq, you’ll need to cast the keys to an array of strings, and then order them as follows:

dailyStatsKeys = dailyStats.Keys.Cast<string>().OrderByx => x).ToList();

or

dailyStatsKeys = dailyStats.Keys.Cast<string>()
.
OrderByDescendingx => x).ToList();

where dailyStats is a hashtable declared and populated elsewhere.

C# System.Func

I needed to create a hook into a class I’m working on that will return a GameObject for a given index.  Now, I could have just built that function into my class, but I’d rather make this class re-usable by other projects down the line (and even other classes within the same project).

public System.Func<int,Transform,TransformrowForRowIndex;

The first two parameters are passed to the function from the calling method, while the third is the returned object.  So in this case, I would invoke the function as follows:

row = rowForRowIndex(r,cachedRow);

Where, r is the index of the row I want to generate, and cachedRow is a row object that has been previously created but is free for use.

You can obviously use different parameters & return type than I am, just remember, the last entry is always the return type, so

public System.Func<bool> isValid;

will return a bool and takes no parameters, while

public System.Func<int,float> rootOfInt;

will return a float and take 1 int as a parameter.

You can also use lambdas to create in-line functions using this syntax:

public System.Func<int,float> rootOfInt = (x) => Mathf.Sqrt(x);

While this is similar to System.Action, the big difference is that System.Func can return a value, System.Action is always type Void.

LINQ, C# and Unity…

Having never ‘learned’ c#, the LINQ syntax sometimes escapes me, and it takes a bit of getting used to, but honestly, it’s worth the price of admission!  I recently needed to find the first object in a list whose Y value was greater than another Y value (basically making sure it was on screen).

My first thought was to use a foreach loop, with a break and a bool flag along with a var to store the index like so:

       bool found = false;
       int rowIndex = 0;

                foreach (float y in rowYPos)
                {
                    if (y>scrollOffset)
                    {
                        found = true;
                        break;
                    }
                    rowIndex++;
                }

This code works, and will return the index of the first entry that exceeds scrollOffset;

However, with LINQ all that becomes:

            int firstRowIndex = rowYPos.FindIndex(x=>x>scrollOffset);

Much shorter, less local vars and pretty self-explanatory.  I didn’t benchmark it to see which was faster, though my hope is that the LinQ method would be, It’s not something that happens often enough to make it a worry.

Handy tip: You’ll need to add a using System.Linq; to the start of the file…

Useful transform property

I was messing around with an idea for a mobile game with Unity, and need to move a character in the direction it was facing.  I’ve done this before by generating a unit vector from the Y angle (it’s a top down view) using sine/cosine.  However, during a hunt for something unrelated, I found:

        playerTransform.localPosition += playerTransform.forward * velocity * Time.deltaTime;

Where, velocity is the speed the player is moving.  Turns out the transform.forward property returns the vector based on the direction of the transform, no more messy code 😀