Category Archives: Programming

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…

Git & Squash

I use Bitbucket & SourceTree as my preferred git solution.  I like the GUI for Sourcetree and Bitbucket lets me store multiple projects on their servers.  One thing I’ve run into is my git repositories getting too big.  This can happen for several reasons – the main one is I forget to copy my default .gitignore to a new project before initializing the repository, and then my Library folder along with lots of other useless files get included.

I’m also going to try and have less commits pushed to the server.  To that effect I’m using the interactive rebase option of Sourcetree.  This will let me make various commits during the day, and then before pushing to the server when I’m done, I’ll squash those commits into one.  That way I’ll merge all the changes and hopefully use less space.

I’m also looking into methods of removing files from the repository that I’ve accidentally added or that I later realize I don’t need and want to remove these files from all history, thus reducing the size of the repository.  I’ve been experimenting with “git filter-branch –tree-filter ‘rm <filename>’ HEAD” and “git filter-branch –index-filter ‘git rm –cached –ignore-unmatch <filename>’ HEAD” and seeing some success, but more experimentation is in order.

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 😀

 

Removing all children from a Transform

I updated my remove all children code to make it less error-prone.  I was having an issue with the children being deleted before the for loop completed, which left some behind.  Using LINQ I was able to adjust it to make a copy of the list of children before I called destroy:

    public static void DestroyAllChildren(Transform parent)
    {
        if (parent!=null)
        {
            List<Transforml = parent.Cast<Transform>().ToList();
            foreach (Transform c in l)
            {
                if (c!=null && c.gameObject!=null)
                {
                    if (c.childCount>0)
                        DestroyAllChildren(c);
                    Destroy(c.gameObject);
                }
            }
            parent.DetachChildren();
        }
    }

Calling parent.DetachChildren() removes the children from the parent immediately.