Website may be up and down over next few months. I'm currently doing a complete overhaul of everything. Going back to simple individual .htm pages, new overall site theme, sanitizing and cleaning up html of all pages and blog posts, attempting to implement a new tooling and publishing system etc etc.

Work Delegation

Published 4/8/2015 by createdbyx in News
Tags:

I came across a YouTube video related to delegating your work and thought I would try and break it down more as it video did not quite make sense to me at first.

https://www.youtube.com/watch?v=6dIuA69p6dY&t=3m45s

Me                   
==========           
5 day work week       
8hrs day           
$25hr wage           
$200 a day           
$1000 week income   

Assistant
==========
1 day work week
8hrs day
$30hr wage
$240 day
$240 week income

(me) $1000 a week – (assistant) $240 a week = (me) $760 at end of week

I earned $760 adjusted weekly income and I worked 5 days a week

I work 5 days a week and spend $240 a week for someone to work one day means I technically put in a 6 day work week but personally earned $760 if I used an assistant to work that extra day. Normally I would have had to work a 6 day a week job but hiring the assistant means I can work a regular 5 day a week job.

In reality if I personally worked for 5 days a week without an assistant I would earn $1000 a week. At 4 days a week at $25hr I make $800 week Monday to Thursday. I hire an assistant at $30hr to work on Friday and they get my $200 a day wage for taking my place and working on Friday. Then on Friday I give them an extra $40 for working on Friday so they earn there $30hr/$240 a day wage.

So at the end of the week I make $800 - $40 = $760 income for a 5 day work week even though I only actually worked 4 days. You earn $760 take home at the end of the week after having paid $40 to not work on Friday. The benefit to me is that for $40 a week expense I can work 4 days a week and have someone else do my job on Friday.

For the assistant they are getting paid more money then I do at $30hr plus I am paying them an additional $40 for that day of work. So the assistant doing my job for one day actually gets paid $5hr more than I would have earned.

Just because I paid someone to work one extra day for me what benefit does that get me? I still work 4 days a week and I have to spend money to hire an assistant to work 1 extra day but in reality where does that get me?

Essentially what I am getting from hiring an assistant is 24hrs of free time and it only costs me $40. And having 24hrs of free time allows me to get other things done. This is of course totally dependent on how valuable the work my assistant does and weather or not they are properly trained and capable of performing the assigned tasks. From the assistants perspective they are making $5hr more then I do but are under more pressure to perform in order to keep the job in order to justify the $30hr wage.


The fallowing script allows you to control fog settings on a per camera basis, allowing you to use say green fog for one camera but red fog for another camera.

Unity 5 package demo is available here CameraFog.unitypackage (46.66 kb)

Camera Fog Screen Shot

CameraFog.cs script

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CameraFog.cs" company="Codefarts">
//   Copyright (c) 2012 Codefarts
//   All rights reserved.
//   contact@codefarts.com
//   http://www.codefarts.com
// </copyright>   
// --------------------------------------------------------------------------------------------------------------------

// Per-camera fog
// This is a simple class that, when added to a GameObject with a camera, allows you to control the fog settings for that camera separately from the global ones. 
// I'd love to hear from you if you do anything cool with this or have any suggestions :)
// Original author: http://wiki.unity3d.com/index.php/User:Tenebrous
// Author website as of 2015: www.tenebrous.co.uk
// Source: http://wiki.unity3d.com/index.php/CameraFog

namespace Codefarts.GeneralTools.Scripts.Camera
{
    using UnityEngine;

    /// <summary>
    /// Modifies a camera to allows you to control the fog settings for that camera separately from the global scene fog or other cameras. 
    /// </summary>
    [RequireComponent(typeof(Camera))]
    [ExecuteInEditMode]
    public class CameraFog : MonoBehaviour
    {
        /// <summary>
        /// The enabled state weather or not fog will be visible.
        /// </summary>
        public bool Enabled;

        /// <summary>
        /// The start distance from the camera where the fog will be drawn.
        /// </summary>
        public float StartDistance;

        /// <summary>
        /// The end distance from the camera where the fog will be drawn.
        /// </summary>
        public float EndDistance;

        /// <summary>
        /// The fog mode that controls how the fog is rendered.
        /// </summary>
        public FogMode Mode;

        /// <summary>
        /// The density of the fog that is rendered.
        /// </summary>
        public float Density;

        /// <summary>
        /// The fog color.
        /// </summary>
        public Color Color;

        /// <summary>
        /// Stores the pre-render state of the start distance.
        /// </summary>
        private float _startDistance;

        /// <summary>
        /// Stores the pre-render state of the end  distance.
        /// </summary>
        private float _endDistance;

        /// <summary>
        /// Stores the pre-render state of the fog mode.
        /// </summary>
        private FogMode _mode;

        /// <summary>
        /// Stores the pre-render state of the density.
        /// </summary>
        private float _density;

        /// <summary>
        /// Stores the pre-render state of the fog color.
        /// </summary>
        private Color _color;
        
        /// <summary>
        /// Stores the pre-render state wheather or not the fog is enabled.
        /// </summary>
        private bool _enabled;

        /// <summary>
        /// Event that is fired before any camera starts rendering.
        /// </summary>
        private void OnPreRender()
        {
            this._startDistance = RenderSettings.fogStartDistance;
            this._endDistance = RenderSettings.fogEndDistance;
            this._mode = RenderSettings.fogMode;
            this._density = RenderSettings.fogDensity;
            this._color = RenderSettings.fogColor;
            this._enabled = RenderSettings.fog;

            RenderSettings.fog = this.Enabled;
            RenderSettings.fogStartDistance = this.StartDistance;
            RenderSettings.fogEndDistance = this.EndDistance;
            RenderSettings.fogMode = this.Mode;
            RenderSettings.fogDensity = this.Density;
            RenderSettings.fogColor = this.Color;
        }

        /// <summary>
        /// Event that is fired after any camera finishes rendering.
        /// </summary>
        private void OnPostRender()
        {
            RenderSettings.fog = this._enabled;
            RenderSettings.fogStartDistance = this._startDistance;
            RenderSettings.fogEndDistance = this._endDistance;
            RenderSettings.fogMode = this._mode;
            RenderSettings.fogDensity = this._density;
            RenderSettings.fogColor = this._color;
        }
    }
}

When the Oculus Rift became a successful Kickstarter it helped launch a world wide interest again in the promise of VR. Even I began to realize that VR could actually become a thing given the advances in technology. But in the subsequent years I can’t help but see all the familiar patterns and signs that led to the downfall of VR way back in the 1990’s.

I hate to be a pessimist but it’s hard not to be as events of recent years have unfolded. I’ve been wanting to write about VR for a while now and finally decided to write down a few of my thoughts on the subject.

But first lets sing the praises of VR shal we

When I caught wind of the Oculus rift it had taken me by surprise. Having been through the disappointment of VR back in the 90’s I was so close to buying a Forte VFX-1 headset but never did. Being a tech geek and budding programmer at the time I know what I’d be getting and I just couldn't justify the cost at the time. The plan was to wait for a newer better cheaper version to come out but nothing ever did.

Funny thing happened between the 1990’s and when Oculus make VR popular again. I completely forgot about VR and I rarely if ever thought about it. It was a distant bitter memory of what could have been. I have resisted the urge to get a smart phone because of bitter resentment towards the way the cell carriers operate, but along came OnePlus and they won me over with a off contract phone that was high end yet still relatively affordable. The OnePlus One was the first cell phone I’ve ever owned and it’s pretty nice. Not having a smart phone meant that I was out of the loop as to what had been going on in the smart phone space. Oculus made me realize that yes indeed smartphones have exploded and along with them the cost of small high resolution screens, and accurate tracking sensors had come down in price significantly. VR could be a real thing again!

Then along comes Sony and there project Morpheus. Wow I thought there maybe something to this VR thing again. All of what I was seeing from Oculus and Sony were very promising and I was getting excited for VR all over again. Then John Carmack a titan in the gamming industry left ID Software to join Oculus and BAM! Drop the mic. VR IS A THING, AND WILL BE A THING! And if John Carmack just joined Oculus, VR was going to be a thing and it was going to be awesome and Oh my F-ing God just take my money NAO!!!. F-Yeah! VR is back baby! Wuhooo.

Then the news broke and the internet was set a blaze. Facebook acquires Oculus.

/facepalm Kill me now. Just, fuck off. FUCK! And I was on such a high. It was fun while it lasted I guess.” Well that was my initial reaction. You see I am not what you would call a social butterfly like billions of others. I don’t use social media because I know what it really is and it has nothing to do with being social. But that is a discussion for another blog post. After taking a deep breath and as much as I hated admitting it, Facebook acquiring Oculus was for the best. It meant Oculus now had almost limitless funding and could really invest heavily in making the best VR headset money could buy at a price that was reasonable. VR was still on track to becoming a reality and a $2 billion investment means investors will want to see a return on that investment.

Then the unthinkable. Seemingly out of the wood work and not to be out done Microsoft announces the HoloLens a augmented reality headset. F**k, now I have to buy two devices. Grumble Grumble. I see HoloLens as the ultimate productivity tool for programming. Not just programming but programming anywhere not just sitting at my desk. And programming with multiple virtual screens hovering around me and around my house. F-Me that would be so awesome and useful. Not to mention for makers and prototyping in 3D right in front of your physical space.

With all the buzz going around with VR & AR devices being announced every other week it seemed the stink of the 90’s had completely wore off. With so many contenders in the race the future looked promising.

… Then the shit just went nuclear …

HTC announces the Vive and a partnership with Valve. Not only that but every article, YouTube video, and podcast that talked about the HTC Vive about the people who got to experience it said it was the best dam VR experience they have ever experienced, even better then what was on offer from Oculus. Just when I thought my anticipation could not get any higher I, … I may have peed a little. :P Just kidding. It wasn't just the announcement it was also the announcement of a shipping date as well. Fall of 2015. At the time Oculus has been sketchy about release dates as was every other VR, AR device maker.

Ho-ly-crap the tech for the Vive and the demos people raved about made me a believer. Sorry Oculus but you just got sent to the back of the bus. I am now leaning towards getting a Vive headset. Wicked tech and a standing experience in VR along with accurate VR controllers. But it is the one demo that made me a believer. That made my heart pulse and my palms sweat. The Portal Tech-Demo where you had to fix the broken robot blew my mind and made me want more. I can not describe in words how awesome that demo looks. It feeds into so many aspects of a tech geeks life. VR, High tech, Information rich, Programming, Engineering, Puzzle solving, accurate 1 to 1 controller interactions and tooling, simply awesome sauce. Everything I love about tech all in one demo. The kind of demo that makes you evaluate your life choices to ensure that you live long enough to experience it first hand. Hahaha!

With all the buzz in the VR, AR space and with all the various peripherals Virtuix Omni, Cyberith Virtualizer, and Sixense STEM system to name a few, there is a lot to be excited over. But then again after you calm down and take a step back, and begin reflecting upon it all, you find the ghosts from the past reaching up to grab hold of you …

Hardware Costs

In my opinion I think there is a strong chance we are going to see deja vu of 90's VR all over again. Yes the big 3 VR headsets Morpheus, HTC Vive, Oculus Rift & maybe OSVR are great but they are suffering the exact same problems that plagued there 90's counterparts.    
 
For one the price. $200->$500-+ for a head set? Automatic fail. I suspect these companies are seeing through a haze of dollar signs as a new market is on the horizon. I’m sure it’s the same haze that over took there 90’s counter parts. They must think because they get away with selling $700+ dollar smart phones they they can get away selling “premium” headsets.  Instead they need to be thinking critically and making investments toward the long term viability of the platform. The only way I see VR truly taking off in a reasonable time frame (IE: the next 3-5 years) with a sufficient install base is if those who can afford it Facebook, HTC/Valve, Sony sell there hardware below cost or at cost for at least the first year or so.  
 
If they can sell a headset at cost for around $99 then there is a chance it can be fast tracked and go main stream faster rather then slowly seeding units over the next decade as the masses slowly adopt future & cheaper revisions of the product. This is critical because without hardware being in the hands of consumers there is no VR market, and there is zero incentive for developers to spend there time making games for it. Period. You absolutely need to get headsets into the hands of people by any means necessary and plant the seeds of a future in VR that you can then profit from, and build upon in the coming decades. 
 
Stop and think about that rumored $300-$500 “premium” price tag for a HTC Vive for a second. What else can you buy for $500 or less? A Xbox One, PS4, even a decent tablet or computer for a casual PC user. Comparatively the complexity of a VR headset is a very very simple display device, where as consoles/PC's contain a motherboard, memory, graphics cards, hard drive, & a pair of controllers etc. Much larger and much more complicated devices sell for less then $350-$400.

That is to say nothing of how much additional cost there is for VR controllers like the Vive wands, or the PS Move wands, or older hardware like the Razer Hydra.
 
Consumers are not stupid. The assumption that they are stupid is stupid. A $200-500 headset which is nothing more then a few sensors and a screen is not going to be a hot ticket item in the eyes of the main stream consumer.

Just look at Samsung's Gear VR selling for a ridiculous $200 and it is nothing more then a hunk of plastic and 2 lenses with the standard tracking sensors, and no screen. Tracking sensors by virtually all accounts are cheap given the rise of smart phones. And you have to buy a Note 4 just to use the dam thing, bringing the total cost to use it even higher.

And the main stream consumer is who you have to convince to kick start a VR future. If VR is kept delegated to a select few dedicated gamers and the like you can expect the VR market to be a slow decade(s) long crawl to adoption. If initial headsets are at a attractive price point that a mainstream consumer can actually afford, after buying a pc or console to power it etc. then you can expect VR to take off in a big way.

UKRifter put it best when he recently stated in one of his DK2 videos that “… if there thinking of charging that kind of premium, I’m kind of out. You know I’ve got kids & expenses in my life … I love VR but I’m not going to be paying those prices. And you’ve got to realize virtual reality is for the poor…

Planning ahead

As of this posting I have yet to see any of these companies offering preorders. I admit it is April 2015 and the earliest headsets are rumored to be available is late 2015 but as a headset maker it would make sense to start polling people to get actual numbers on how many people are planning to buy a headset at launch. It’s the same problem that plagued the Wii and other hardware with lack of stock at release and months thereafter.

Headset makers need to be smart about how many units they can expect to ship at launch and if it were up to me I would start preorders and taking peoples money by no later then July 2015 or early fall. That way you know exactly how many people are buying and exactly how many headsets you need to get ready for launch as well as how many additional headsets to prep for the main stream retail sales.

It’s 2015 and I can’t stand it when companies don’t take advantage to the global internet enabled customer base by polling or setting up preorders in order to ensure there product is going to be available to people on day one. Creating artificial scarcity or introducing “premium” headsets is I’ll advised when trying to kick start a totally new platform.

Software & Content

You also need to take into account content. There will be very little content available at launch and for the next year or two after launch. Dropping upwards of $500 and having only a small handful of VR games available to play is not going to cut it. Let alone games the consumer would want to play. People are not going to justify a $500 headset if there is no content for it especially main stream consumers. But if it was $99? Yes you would, especially knowing that there is more content on the way.

I have to admit that it frustrates me to no end to see argument after argument on various forums and YouTube about the technical aspects of VR from people who are not technically inclined or trained. They seem to have this view that somehow they are going to see high detail high poly count AAA games for VR games and that it is going to cost a fortune in PC hardware to support or that the consoles don’t have enough horsepower to support VR. A ridiculously stupid argument.

Initial VR games are going to be low poly, cartoony, wow style graphics in order to maximize the supported hardware that is already out there. I suspect you can see the quality of VR games to be a few years behind there standard non VR counterparts.

It’s only been roughly 2-3 years since the Oculus Kickstarter so developers have not been working on VR titles for very long. Taking into account that developers have been waiting to see what becomes of the hardware. I’d say until the big three threw there hat into the ring Sony, Oculus, HTC, developers have really only just started working on new titles in the last year. It takes a good 2-5 years to develop a game and that does not even take into account the additional challenges of developing for VR. Even adapting existing titles to VR can be tricky.

I can’t imaging that there will be no more then say 12 to 24 decent VR titles at launch and a slew of half baked demos and mini games. Not a lot for a consumer to justify a $200-$500 price tag.

Conclusion

Establishing a new VR market is a huge uphill battle. On one hand you need headsets in the hands of enough consumers to make the platform viable for developers to make content for it. On the other there is technically a lot of content out there that can be adapted to VR but with no headsets in the hands of consumers developers are not likely to take the time to adapt there preexisting titles for a platform that has yet to see adoption. Chicken before the egg scenario.

For VR to be considered a success within the next 5 years and achieve widespread adoption headsets need to be priced under the $150 range and absolutely no more. I hope I’m wrong but realistically when I take my VR blinders off and take into account all the factors I just don’t see VR going main stream and achieving mainstream adoption any time soon. Like the next decade soon. Just as I think there is a good chance the big three VR makers could poison the well once more and make VR a difficult sell for widespread adoption.

When you put it all together all I’m really seeing is very high prices to get into VR not to mention additional costs for VR controllers, a decent or high end PC depending on your gamming preferences, and a industry seemingly all to ignorant of history and setting them selves up to fail.

Maybe I’m wrong and I hope I am but time will tell if the next 5 years VR has gotten a well established foot hold and is on it’s way to becoming main stream. As someone who has been let down by the promise of VR in the 90’s I’m not holding my breath.


The unity 5 documentation has a couple of handy reference charts for when you need to help determining what material values to set to get a particular look and feel.

http://docs.unity3d.com/Manual/StandardShaderMaterialCharts.html


With the introduction to Unity 5 there comes some api changes. Specifically this foot note was interesting “[2] in Unity5 we also cache the transform component on the c# side, so there should no longer be a performance reason to cache the transform component yourself.

I decided to test it out by writing a few performance test scripts and comparing performance numbers. Below is a screen shot of my results along with the scripts used.

As you can see caching a reference to the transform component in the Start method then using that reference is still faster then calling “this.transform” directly albeit only slightly by about 10-20 ticks. And calling “this.GetComponent<Transform>()” is almost twice as slow.

Unity5TransformPerformance

The code for the PerformanceTesting class is availible here.

TransformCachedGetComponentPerformance script

    using UnityEngine;

    public class TransformCachedGetComponentPerformance : MonoBehaviour
    {
        private Transform reference;

        /// <summary>
        /// Awake is called when the script instance is being loaded.
        /// </summary>
        public void Awake()
        {
#if PERFORMANCE
            var perf = PerformanceTesting.PerformanceTesting<string>.Instance;
            perf.Create("UnityTesting/TransformCachedGetComponentPerformance/Update");
#endif
        }

        /// <summary>
        /// Start is called just before any of the Update methods is called the first time.
        /// </summary>
        public void Start()
        {
            this.reference = this.GetComponent<Transform>();
        }

        /// <summary>
        /// Update is called every frame, if the MonoBehaviour is enabled.
        /// </summary>
        public void Update()
        {
#if PERFORMANCE
            var perf = PerformanceTesting.PerformanceTesting<string>.Instance;
            perf.Start("UnityTesting/TransformCachedGetComponentPerformance/Update");      
#endif

            var rnd = new System.Random();
            this.reference.localPosition = new Vector3(rnd.Next(-3, 3), rnd.Next(-3, 3), rnd.Next(-3, 3));

#if PERFORMANCE
            perf.Stop("UnityTesting/TransformCachedGetComponentPerformance/Update");
#endif
        }
    }

TransformGetComponentPerformance script

    using UnityEngine;

    public class TransformGetComponentPerformance : MonoBehaviour
    {
        /// <summary>
        /// Awake is called when the script instance is being loaded.
        /// </summary>
        public void Awake()
        {
#if PERFORMANCE
            var perf = PerformanceTesting.PerformanceTesting<string>.Instance;
            perf.Create("UnityTesting/TransformGetComponentPerformance/Update");
#endif
        }
        
        /// <summary>
        /// Update is called every frame, if the MonoBehaviour is enabled.
        /// </summary>
        public void Update()
        {
#if PERFORMANCE
            var perf = PerformanceTesting.PerformanceTesting<string>.Instance;
            perf.Start("UnityTesting/TransformGetComponentPerformance/Update");
#endif

            var rnd = new System.Random();
            this.GetComponent<Transform>().localPosition = new Vector3(rnd.Next(-3, 3), rnd.Next(-3, 3), rnd.Next(-3, 3));

#if PERFORMANCE
            perf.Stop("UnityTesting/TransformGetComponentPerformance/Update");
#endif
        }
    }

TransformFieldPerformance script

    using UnityEngine;

    public class TransformFieldPerformance : MonoBehaviour
    {
        /// <summary>
        /// Awake is called when the script instance is being loaded.
        /// </summary>
        public void Awake()
        {
#if PERFORMANCE
            var perf = PerformanceTesting.PerformanceTesting<string>.Instance;
            perf.Create("UnityTesting/TransformFieldPerformance/Update");
#endif
        }

        /// <summary>
        /// Update is called every frame, if the MonoBehaviour is enabled.
        /// </summary>
        public void Update()
        {
#if PERFORMANCE
            var perf = PerformanceTesting.PerformanceTesting<string>.Instance;
            perf.Start("UnityTesting/TransformFieldPerformance/Update");
#endif

            var rnd = new System.Random();
            this.transform.localPosition = new Vector3(rnd.Next(-3, 3), rnd.Next(-3, 3), rnd.Next(-3, 3));

#if PERFORMANCE
            perf.Stop("UnityTesting/TransformFieldPerformance/Update");
#endif
        }
    }

The fallowing code snip is designed to take in a flat list of file paths (or similar data) and produce a hierarchy of tree nodes representing those file paths.

        /// <summary>
        /// Constructs a nested hierarchy of types from a flat list of source types.
        /// </summary>
        /// <typeparam name="TSource">The source type of the flat list that is to be converted.</typeparam>
        /// <typeparam name="TReturn">The type that will be returned.</typeparam>
        /// <typeparam name="TPart">The type of the art type.</typeparam>
        /// <param name="sourceItems">The source items to be converted.</param>
        /// <param name="getParts">A callback function that returns a array of <see cref="TPart"/>.</param>
        /// <param name="comparePart">The compare part callback.</param>
        /// <param name="getChildren">The get children callback.</param>
        /// <param name="addChild">The add child callback.</param>
        /// <param name="createItem">The create item callback.</param>
        /// <returns>Returns an collection of <see cref="TReturn"/> representing the hierarchy.</returns>
        /// <exception cref="Exception">A delegate callback throws an exception. </exception>
        private static IEnumerable<TReturn> ToHierarchy<TSource, TReturn, TPart>(
          IEnumerable<TSource> sourceItems,
        Func<TSource, TPart[]> getParts,
        Func<TReturn, TPart, bool> comparePart,
        Func<TReturn, IEnumerable<TReturn>> getChildren,
        Action<IEnumerable<TReturn>, TReturn> addChild,
        Func<TPart[], int, TSource, TReturn> createItem)
        {
            var treeModels = new List<TReturn>();
            foreach (var keyName in sourceItems)
            {
                IEnumerable<TReturn> items = treeModels;
                var parts = getParts(keyName);
                for (var partIndex = 0; partIndex < parts.Length; partIndex++)
                {
                    var node = items.FirstOrDefault(x => comparePart(x, parts[partIndex]));
                    if (node != null)
                    {
                        items = getChildren(node);
                        continue;
                    }

                    var model = createItem(parts, partIndex, keyName);
                    addChild(items, model);
                    items = getChildren(model);
                }
            }

            return treeModels;
        }

An example of how one could use the ToHierarchy method would be like this …

        var separator = new[] { Path.AltDirectorySeparatorChar.ToString(CultureInfo.InvariantCulture) };
        // paths varible could be something from Directory.GetDirectories method for example.
        var nodes = ToHierarchy<string, TreeViewNode, string>(
            paths.OrderBy(x => x),
            x => x.Split(separator, StringSplitOptions.RemoveEmptyEntries),
            (r, p) => string.CompareOrdinal(r.Name, p) == 0,
            r => r.Nodes,
            (r, c) => ((List<TreeViewNode>)r).Add(c),
            this.CreateTreeNode);

        private TreeViewNode CreateTreeNode(string[] parts, int index, string source)
        {
            var node = new TreeViewNode() { Name = parts[index] };
            node.Value = string.Join(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), parts, 0, index + 1);
            if (index == parts.Length - 1)
            {
                node.Name = Path.GetFileName(source);
            }

            node.IsFile = File.Exists(node.Value);
            return node;
        }

Where paths is a array of file paths from say Directory.GetFiles.


Source: http://stackoverflow.com/questions/616718/how-do-i-get-common-file-type-icons-in-c

    public static class FileIcon
    {
        [DllImport("shell32.dll")]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

        [StructLayout(LayoutKind.Sequential)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        private const uint SHGFI_ICON = 0x100;
        private const uint SHGFI_LARGEICON = 0x0; // 'Large icon
        private const uint SHGFI_SMALLICON = 0x1; // 'Small icon

        public static System.Drawing.Icon GetLargeIcon(string file)
        {
            var shinfo = new SHFILEINFO();
            var hImgLarge = SHGetFileInfo(file, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), FileIcon.SHGFI_ICON | FileIcon.SHGFI_LARGEICON);
            return System.Drawing.Icon.FromHandle(shinfo.hIcon);
        }

        public static System.Drawing.Icon GetSmallIcon(string file)
        {
            var shinfo = new SHFILEINFO();
            var hImgLarge = SHGetFileInfo(file, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), FileIcon.SHGFI_ICON | FileIcon.SHGFI_SMALLICON);
            return System.Drawing.Icon.FromHandle(shinfo.hIcon);
        }
    } 

There are some instances when you may need to lock the mouse cursor to the screen. For example rotating the camera where you would press down on the right mouse button then drag the mouse to rotate the camera. If you wish to hide the mouse cursor and lock it to the screen while dragging you can use Screen.lockCursor.

using UnityEngine;

public class lockCursorExample : MonoBehaviour
{
    void DidLockCursor()
    {
        Debug.Log("Locking cursor");
    }

    void DidUnlockCursor()
    {
        Debug.Log("Unlocking cursor");
    }

    private bool wasLocked;

    void Update()
    {
        if (!Screen.lockCursor && this.wasLocked)
        {
            this.wasLocked = false;
            this.DidUnlockCursor();
        }
        else if (Screen.lockCursor && !this.wasLocked)
        {
            this.wasLocked = true;
            this.DidLockCursor();
        }

        if (Input.GetMouseButtonDown(1))
        {
            Screen.lockCursor = true;
        }

        if (Input.GetMouseButtonUp(1))
        {
            Screen.lockCursor = false;
        }
    }
}

Ever wish you could have a tool tip appear when hovering your mouse over a control in the inspector? Well look no further then Unity’s ToolTip attribute that you can apply to your MonoBehaviour’s fields!

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    [Tooltip("Health value between 0 and 100.")]
    public int health = 0;
}

Sometimes it is handy to keep a game object alive for as long as your game is running. In order to prevent your object from being destroyed when loading a new scene use GameObject.DontDestroyOnLoad and your game object will persist between scene changes.


Created by: X

Just another personal website in this crazy online world

Name of author Dean Lunz (aka Created by: X)
Computer programming nerd, and tech geek.
About Me -- Resume