Category Archives

Setting the device brightness on Windows with WPF

.NET, Technical stuff, Windows 10, Windows 7, Windows 8, Work, WPF

I am working on a project which I can’t really detail, but one aspect caused me a few headaches. Finally I reached out to the Windows team at Microsoft and got great help from Katie Anderson who works on the brightness team. This was quite tricky, and we had to have a couple of roundtrips before we managed to find a way that worked.

Well, why?

In the application I am working on, it is necessary for the user to set the device brightness from the application itself. You might wonder why, because most Windows devices have hard keys to set the monitor brightness. For example on a Surface, you can use the Fn-Del and Fn-Backspace key combinations to alter the brightness of the screen. Or you can of course swipe from the right side and use the Brightness button to change the value in the Action Center.

However on that particular project, the user doesn’t have access to the keyboard, nor to the Action Center. This is a kind of kiosk scenario if you will where many of the Windows features are deactivated by policies, and no hard keyboard is provided. I had to find a way to do this programmatically.

First approach: Not so good

At first I thought I would have my application’s main window run in full screen and set a black Rectangle on top of everything, and change the Rectangle’s opacity in my code. That worked well but of course it wouldn’t work if other applications were in the foreground (yes, I forgot to mention, it’s a kiosk app which can start other apps and put them in the foreground…).

Second approach: Better but not great

OK, no problems I thought, let’s have my app open a modal full screen window which is always on top. I will then have this window made insensitive to touch or mouse clicks with the following code. Finally, this window will have the black Rectangle and be on top of everything all the time.

public static class WindowsServices
    private const int GwlExstyle = -20;
    private const int WsExTransparent = 0x00000020;

    public static void SetWindowExTransparent(IntPtr hwnd)
        var extendedStyle = GetWindowLong(hwnd, GwlExstyle);
        SetWindowLong(hwnd, GwlExstyle, extendedStyle | WsExTransparent);

    static extern int GetWindowLong(IntPtr hwnd, int index);

    static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

This worked OK but somehow it was not satisfying. I really wanted to have a solution where my app would modify the actual device brightness. There are a few reasons why the client also wanted that, and so I started to investigate deeper. Unfortunately, Bing searches (and the equivalent Google searches) didn’t really return anything satisfactory.

Using Powershell

After searching a bit, I got a first clue that what I wanted to achieve was doable: You can query and modify the device brightness from Powershell with the following script:


PS C:> Get-Ciminstance -Namespace root/WMI -ClassName WmiMonitorBrightness


PS C:\Users\lbugn> $monitor = Get-WmiObject -ns root/wmi -class wmiMonitorBrightNessMethods
PS C:\Users\lbugn> $monitor.WmiSetBrightness(50,10)

If you run these commands in Powershell, you will marvel at the result: Yes it does work and the screen’s brightness is modified. Great Scott, I am on the right track! The key to this is the WMI (Windows Management Interface) class WmiMonitorBrightness.

Converting to .NET

The next step was obvious: I needed to convert the Powershell script to some usable .NET code. Unfortunately, easier said than done. This is where I reached out to Microsoft for help and thankfully Katie really followed through and after a few iterations we got it to work.

First she used the WMI Code Creator tool to convert the Powershell script to .NET. I had no idea that such a tool existed, but then again I never had to dive so deep in the entrails of Windows. Unfortunately when running the code that the tool created (which I won’t post here to avoid confusion), I got some errors. One more roundtrip to Redmond (via email) and Katie found the way: The following code will indeed modify the brightness of the screen, yay!!

public static class WindowsServices
    private static ManagementObject _brightnessInstance;
    private static ManagementBaseObject _brightnessClass;

    static WindowsServices()
        // Querying the Windows service to get the Brightness API.
        var searcher = new ManagementObjectSearcher(
            "SELECT * FROM WmiMonitorBrightness");

        var results = searcher.Get();
        var resultEnum = results.GetEnumerator();
        _brightnessClass = resultEnum.Current;

        // We need to create an instance to use the Set method!
        var instanceName = (string)_brightnessClass["InstanceName"];
        _brightnessInstance = new ManagementObject(
            "WmiMonitorBrightnessMethods.InstanceName='" + instanceName + "'",

    public static int GetDeviceCurrentBrightness()
        // Getting the current value.
        var value = _brightnessClass.GetPropertyValue("CurrentBrightness");
        var valueString = value.ToString();
        return int.Parse(valueString); // Direct cast fails.

    public static void SetDeviceBrightness(int newValue)
        if (newValue < 0)
            newValue = 0;

        if (newValue > 100)
            newValue = 100;

        var inParams = _brightnessInstance.GetMethodParameters("WmiSetBrightness");
        inParams["Brightness"] = newValue;
        inParams["Timeout"] = 0;
        _brightnessInstance.InvokeMethod("WmiSetBrightness", inParams, null);

I made a small sample here which gets the current value of the screen brightness and then increases it by 10% every time you click on a button. When you reach 100%, it goes back to zero on the next click. Simple enough, and does the trick.

I hope that this will be useful to a reader looking for the same feature. I’d love to be the first one to ever blog about this. I doubt that I am, and probably someone will point me to the article that I never found :) but seriously, I really couldn’t find any mention of something like that on the whole WWW.

Happy coding!

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)

Share on Facebook

Two millions #mvvmlight downloads

.NET, MVVM, Technical stuff, Universal Windows Platform UWP, Work, WPF, Xamarin, XAML

Sometimes between last week and this week, we crossed a threshold: Two millions MVVM Light downloads.

I don’t have many metrics about MVVM Light, because the toolkit itself is not instrumented in any way. You get the raw binaries without added sugar :) So the only numbers I can rely on are the number of downloaded copies, either on Nuget or as the VSIX extension for Visual Studio. Obviously this doesn’t say much about the number of applications created with MVVM Light, since once the VSIX is downloaded, every File / New Project command creates a new app without any download. Still, it’s been interesting to see the evolution in downloads since I started to track the numbers.

Recently, I had a memory on my Facebook wall reminding me that 2 years ago, I was posting about 500’000 downloads, just before my Visual Studio Live sessions in Las Vegas. Two years later I was in Vegas again, for VS Live again, and about to cross two millions. Clearly the curve went up quite a bit. I tried to analyze what was the most significant change, and I think the port to Xamarin definitely played a significant role there. I also saw an uptake in interest in conference submissions since MVVM Light is truly cross platform, especially since Xamarin Evolve 2014 where I had a session. Since then a lot more sessions were given about Building Truly Universal Applications with MVVM Light, and quite a few full rooms too.

Tracking the downloads

As I mentioned, it is difficult to track downloads in a significant manner. There are automated build stations that will restore Nuget packages every so often. On the other hand there are people who download the Visual Studio extension once and create new applications without downloading anything. The only significant metric, I guess, is the evolution in downloads over time. Here is a chart (click to enlarge):


Right now I track downloads on the following pages:

What’s coming

Currently I am working on the following topics:

  • A post about Working with MVVM Light in Visual Studio 2017. This is a pretty long post, which will also end up in the documentation pages. It will also explain how the sample applications (created by the templates) work and what features they demonstrate.
  • Improving the project template for WPF. I want to add more features there and be on par with what I have for Windows 10, iOS and Android.
  • Adding a project template for iPad and iOS Universal.
  • MVVM Light for Xamarin Pluralsight course. No ETA on this at the moment, sorry.

And of course the backlog is still active! Don’t hesitate to send your feedback :)

Happy coding!

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

New role, new responsibilities, same passion! Embracing 2017

IdentityMine, Technical stuff, Valorem, Work
No Comments

As I am writing this, I just came back from Kansas City, Missouri, where I met with a few people who are going to be an integral part of my next adventure.

I often tell this story: When I was working for Siemens and my passion for software was facing a difficult time, due to the frustrations of not being able to render my designers’ visions in HTML/CSS, I was sent to Las Vegas to attend MIX06, the first ever MIX conference, and to discover Windows Presentation Foundation and Expression Blend, which became two passions of mine. Working with the various teams at Microsoft responsible for these amazing new products, I started blogging about my experiences. This led Microsoft to give me the MVP award in 2007 (and every year since then), this also led Sams publishing to contact me and ask me if I wanted to write a book about Silverlight 2 which Microsoft had just started in preview. I started speaking at conferences, first within Siemens and then at various conferences. This became a side activity that was often crossing paths with my day work as a software developer.

My public speaking, blog writing, and other publishing activities were just something I felt like doing. It was profitable both for the firm I was working for, IdentityMine, and for myself as I was building my personal brand.

In May 2016, IdentityMine was acquired by Valorem, and our activities started encompassing more than the client application development we were known for. Valorem had always been very active in back-end development, from Sharepoint to Azure to Office365 to PowerBI to many other areas which I know of, but which I don’t know much about. This year, I will be starting a new role, which neither Valorem nor pre-acquisition IdentityMine has ever officially had: That of Senior Technical Evangelist.

In this role, I will educate myself in all the various areas where we do business. I want to be able to talk to anyone in the firm and have an understanding of what they are doing. Then, I will be responsible to give visibility to all the amazing people who work at the new Valorem. This includes blogging about activities that we do, projects that we work on, but also exciting new activities which I cannot talk about yet (but video should be involved, fun!!). I also want to make people proud of what they are doing, and to teach them how to talk about it, maybe at local user groups, maybe at conferences, maybe writing for the Valorem blog, maybe writing articles for magazines etc. Teaching people to manage their personal brand, coaching them to put themselves out there, work with the community, etc.

Everyone at the executive level is very excited because that is something that we just didn’t do before, not in any official capacity. This is a new role, which should allow me to explore and try new things, see what’s working. It should also allow me to visit all our various locations, talk to the people, understand what they do, and get more knowledgeable on all the areas that we are covering (which is a lot). Also, it will give me the opportunity to look into new areas that might be interesting for the firm, such as Cognitive services, Blockchain, and many more.

Next to this, I will of course continue to support our sales teams in pre-sales operations, as well as give a hand in architecture or coding for our development teams where needed. And of course I will continue to support our European operation, which as small as it is right now is still generating enough leads and projects to keep things interesting.

I’ll be looking forward to meeting a lot of Valorem employees in the months to come and work with all of you. Please do not hesitate to reach out to me if you have questions, remarks or suggestions. This role is for you in the first place.

Happy coding

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

A good start in 2017: NDC London and a World of Devices

HoloLens, MicrosoftBand, NDC, Technical stuff, Work
No Comments

Sorry for the late post, I wanted to post this earlier but then a lot happened (getting sick didn’t help and a trip to Kansas City where I am typing this from).

Last Wednesday I flew to London City airport to speak at the first conference of the year: NDC London. The Norwegian Developer Conference started in Oslo but quickly expanded to other locations. I spoke at NDC a few times but I had not been able to speak there for a while. I was happy that the organizers and I could agree on a topic that drew a respectable crowd of nice people coming to hear me talk about A World of Devices. All the documents are here!

This talk is a little different than my usual talks. No code! but a lot of anecdotes from my past as a (huge) geek, who tried most devices that attracted my attention for the past 20+ years. For me it all started when I got a Casio device in which I could store my contacts and calendar information. There was little to no connectivity (this was before I even went online). Then I seriously considered purchasing a Newton! I even went to the store to see it and really hesitated. I loved the handwriting recognition. I really wanted one but I just couldn’t pay for it, no way. Later, my dream came true: I bought a Palm Professional. This was the second generation of Palm devices. I had to order it specially from a US website (in the mean time I had gotten internet access at work and then at home). I can’t say how much I loved this device and the many Palm devices I bought after that. I became super proficient in Graffiti handwriting, so much so that even started writing this way on paper (the Ts were particularly funny).

There are a lot of anecdotes from these pioneer times (like my first mobile internet connection, which I got from my Palm to a Siemens mobile phone through the Infrared port and then to the mobile network. It took ages to negotiate the handshakes and of course typically as soon as you were connected something happened and the IR connection would get cut, for example a bump in the railroad or something similar).

I drew on this experience and all the other amazing devices I either used or coded for (or both) to prepare what I think is an informative and interesting session with a lot of demos: Cortana; Inter-device communication (Microsoft Band connecting through Bluetooth to a PC and controlling a 3D scene thanks to the Accelerometer sensor); Windows Continuum; and of course Microsoft HoloLens.

Thanks to everyone who came by, I really appreciated your presence. Thanks also to everyone who came later to speak to me regarding MVVM Light, WPF, Silverlight, Xamarin or any other topic. It’s always such a pleasure to connect with people all around the world and have interesting discussions.

As always, I created a page on my website for this presentation. There you will find the slides, the link to the Her trailer video as well as the GitHub repo for the Microsoft Band sample.

Happy coding and happy 2017!

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

Le matériel pour ma présentation “HoloLens 101” du DevDay à Mons

Conferences, HoloLens, Personal, Technical stuff, Work
No Comments

J’ai eu beaucoup de plaisir à participer à l’événement DevDay à Mons en Belgique. Cela fait déjà quelque temps qu’Olivier Matis me demande de participer, et malheureusement cela n’avait pas été possible pour des questions de temps. Enfin cette année j’ai pu dire oui. Connaissant au moins certains membres de l’équipe organisatrice, je me réjouissais vraiment de faire le voyage pour cette ville que je ne connaissais pas encore.

Après un court vol et une heure en train, je me suis donc retrouvé dans cette ville dont le nom signifie « montagne », ce qui est assez drôle pour un Suisse. Très jolie ville, que j’ai traversée à pied dans un froid de canard, mais en admirant la cathédrale et la place centrale avec l’hôtel de ville. Au soir, souper avec certains des speakers et organisateurs, dans une super ambiance, et avec de la bonne bière.

Le lendemain, j’avais l’honneur de donner la première session dans une salle de cinéma à l’écran géant, une chouette expérience pour un speaker. Quelques soucis de micro, et un peu de stress parce que j’ai décidé de donner la session en français… Ca peut paraître drôle mais je n’ai pas l’habitude de parler de programmation en français… d’habitude c’est l’anglais, voire l’allemand.

Au final, tout s’est bien passé, et j’ai pu montrer les différences entre VR, AR, MR, parler de l’environnement de développement, et montrer une démo d’une petite appli commencée depuis zéro, pour donner un petit peu le goût de la programmation 3D. Enfin, j’ai fini la session avec des démos d’applications que nous développons pour des clients.

La fin de la journée s’est passée à faire des démos HoloLens et discuter avec plein de monde dans une super ambiance. Un petit tour en Tesla X de démonstration avant de reprendre le train et l’avion…

Un grand merci aux organisateurs pour l’invitation et le super travail sur place, ainsi bien sûr aux nombreux spectateurs qui sont venus assister à la session et me parler par la suite.

Vous trouverez le fichier PowerPoint, le code ainsi que quelques vidéos de démonstration sur mon site.

Amitiés à tous

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

Code and slides posted for my latest talks

.NET, Conferences, HoloLens, MVVM, Technical stuff, Universal Windows Platform UWP, UX, Windows 10, Work, Xamarin, XAML
No Comments

October and November have been quite busy with travel. I talked at a few occasions in some cool events and want to take a moment to share the code and slides below:

Xamarin Dev Day, Zurich, Switzerland

I love the concept of the Xamarin Dev Day. It’s a great way to reach out to local communities and have a day of fun teaching and training with Xamarin content. This year I took part to the Zurich, Switzerland occurrence. It definitely didn’t hurt that it was help in a very cool space, under a train viaduct in the previously industrial area of the city, which is these days a pretty cool place to live and work.

I held my talk titled “Building truly cross platform applications with Windows, Xamarin and MVVM Light” which comments on the fact that the so called “UWP” (Universal Windows Platform) applications are only for Windows (hence the W) and that if you want to target mobile iOS and Android devices, you need something more. Xamarin and MVVM Light are great solutions in this scenario, because they maximize the amount of code that can be shared, all the while increasing the testable surface of the application. You can find the code and slides at this page.

KC .NET User Group & Xamarin KC Dev, Kansas City, Missouri

You might have read that the company I joined in 2008 (IdentityMine) was acquired this year by a company based in Kansas City named Valorem Consulting. On November 1st and 2nd, I spent time at the head office to meet with a maximum of new colleagues. It was a nice stay in a city (and state) I had never visited before. In fact I even “visited” two states during that stay, because Kansas City is laid over Missouri and Kansas! Earlier on I had tweeted about me visiting KC, and the local .NET developer user group contacted me and asked if I wanted to speak at a user group meeting on that evening. Of course the answer was a resounding yes! And the best part is that the Xamarin KC user group also joined the fun for their first ever joint event. We had a great attendance with a full room of about 65 people, and a very nice interaction. After the event, a small group gathered at a local bar and we had pie and drinks (I had a root beer float, because why not). Excellent way to make new friends in a new city! I also held my talk “Building Truly Universal Applications with Windows, Xamarin and MVVM Light”.  You can find the slides and code here.

DevIntersection Europe, Haarlem, The Netherlands

Right after my return from the US (with the visit to Kansas City, a few days in the office in Seattle and then the MVP and Regional Directors Summit in Bellevue/Redmond), I had another short trip to the Netherlands. I spoke at the DevIntersection conference in Haarlem, a small city not far from Amsterdam. The location was superb, a convention center close to the historical center of the city, the hotel was great too (though the bed was wayyyyy too soft for me :) and the audience was very nice. It is definitely smaller than DevIntersection in the US (where they have events in Vegas and Orlando), but I had a good albeit small audience nonetheless and some great interactions with attendees and fellow speakers.

I spoke about the Windows 10 Universal Windows Platform, a dense session which contains information about creating a new UWP app; adapting the user interface to the various form factors, resolutions, orientations etc; porting classic windows applications to the Windows 10 ecosystem with the Desktop App Converter (also known as Centennial bridge); the Windows Continuum; and Microsoft HoloLens. Unfortunately because of unknown technical issues, I was not able to stream the HoloLens output to my phone nor to my Surface like I used to do. Unfortunately we ran out of time before I was able to solve the issue (which would probably have required restarting the HoloLens and the phone). I want to apologize to the audience for this technical glitch. I hope that the people who joined me later for a quick trial of the HoloLens were happy anyway, and that the others didn’t go back home with a bad image of this amazing technology :) I recorded a few videos showing the various demos I wanted to give, you can find all the material including code and slides on this page.

Thanks all for attending and happy coding!

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

#Microsoft #Experiences in Paris: Code and slides

.NET, Conferences, HoloLens, MVVM, Technical stuff, Windows 10, Work, WPF, Xamarin, XAML
No Comments

Last week I had the pleasure of taking the TGV from Zurich to Paris, and after a quick 4 hours of comfortable travel, to make my way to the Porte Maillot and the Palais des Congrès.

TL;DR: All slides and source code is available from here.

A podcast

After a good night sleep I made my way to the speakers lounge and prepared the last steps for my talk. Then I took a moment to head to the meeting room where the Live Tiles podcast was being recorded. A band of podcasters got together and talked about the future of Microsoft. It was so nice to “see these familiar voices” in action. Even nicer when Christophe (Toss .NET) and Denis saw me and pulled me in to talk about HoloLens and our experiences with this device. You can hear the recording here, my contribution starts at 36:30.

My talk: Really universal apps with Xamarin and MVVM Light

My talk was titled (in French) “Construisons des applications vraiment universelles avec Windows, Xamarin and MVVM Light”. This favorite topic of mine shows how you can structure an application to share a maximum of code without any compromises. You can build healthy layers of Model and ViewModel, unit test them so you can feel secure about not breaking anything with future changes. Then you can build a thin layer of real native user interface for any supported framework with XAML or Xamarin (Windows Presentation Foundation, Windows 10 Universal, Xamarin.iOS, Xamarin.Android). And if you are in an enterprise scenario and looking for maximum productivity, you can also of course use Xamarin.Forms and render the same UI to all supported platforms.

The MVVM Light Toolkit assists you in these tasks, notably by providing a Data Binding framework for Xamarin.iOS and Xamarin.Android, as well as components that make it very easy to connect a list control to an ObservableCollection, with automatic refresh in case the collection changes. This open source toolkit is in it’s version 5.3, has been downloaded almost 1.7 million times and is even used by Microsoft to build parts of Windows 10.

I was really pleased when I headed to my conference room and saw a long queue in front of the entrance. I gave my talk to a standing room of about 270 people, and loved the interaction during and after the talk. A lot of very positive feedback, and we stayed and talked until the hostess kicked us out of the room :)

Thank you to everyone who came and made this a memorable moment. You will find all the details of the talk, the slides and the source code from this portal.

Some tea

Before I made my way to the Palais des Congrès, I took a pit stop at one of the most wonderful shops on Earth: the Mariage Frères tea store. This old fashioned store is stock full of amazing teas from all over the world. It’s a must-visit if you are a tea enthusiast or if you just want to spend a moment living in an atmosphere of luxury and pleasure.

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

Slides and code samples for VS Live Redmond

HoloLens, MVVM, Technical stuff, Universal Windows Platform UWP, VSLive, Windows 10, Work, WPF, Xamarin, XAML
No Comments

VS Live just took place in Redmond, and I had a great time. I had three sessions in one day, and I was really exhausted in the evening, but it was absolutely worth it. Speaking in Building 33 (the conference center on Microsoft campus) was an amazing experience. I have spent so many hours in this building, listening to amazing speakers of Microsoft and others, during MVP summits and other events… so really it was quite magical to be on the speaker side this time, in room St Helens.


Thanks to every one who came to my talks! I hope it was informative and useful, and that it encourages you to try those technologies and techniques.

Here are the pages for the talks I gave:

Windows Presentation Foundation (WPF) 4.6
Windows Presentation Foundation is what people are using to build real applications for the enterprise, the industry, the workplace, and for every situation where Windows 10 Universal isn’t quite ready yet. Far from being dead, WPF is 10 years old this year, and it’s still alive and kicking. It gives Universal Applications a run for their money. In this session, you’ll learn what is new in Windows Presentation Foundation, where it’s going in the future, and what you can achieve with WPF that Universal Application developers can only dream of. We’ll also see how these two roads cross and how existing WPF applications can be brought to Windows 10 using the Centennial bridge. Finally we’ll discover new features and tools recently implemented for WPF developers.

Windows 10 – The Universal Application: One App To Rule Them All?
Windows 10 and the Universal Windows Platform offer a lot of productivity and flexibility around targeting the broad set of devices that run Windows. As a developer, you have a lot of choice–from building a single binary that is identical on all devices, through to an app that adapts to the type of device and on to the point of building an entirely different app for each class of device. What’s the right thing to do? How should you think about building the “One App to Rule Them All?” What are the design and implementation trade-offs you need to consider? This session dives into these areas with a hands-on approach and shows what it really means to be building apps across families of Windows devices that have different capabilities. We will also talk about bridges (and especially the iOS Bridge to Windows 10), and new platforms such as Continuum and HoloLens (with live demos).

Building Truly Universal Applications with Windows 10, Xamarin and MVVM
With Windows 10 supporting an unprecedented number of platforms and form factors (from IOT to phones to tablets to laptops and desktops to XBOX and SurfaceHub, and even the new HoloGraphic computer HoloLens), the name ‘Windows 10 Universal application’ is fairly accurate. But to be honest, shouldn’t a truly Universal application run on Windows 7, iOS and Android devices too? Thankfully, this is possible thanks to a clever architecture pattern named Model-View-ViewModel, the .NET portable class libraries and the Xamarin frameworks. With these tools, we can structure an application so that most of the code is shared across all the platforms, and then build truly native UI that adapts without any compromises to the device it runs on. In this session, we will understand exactly how such universal applications are built. Laurent Bugnion, a XAML/C# expert, Microsoft and Xamarin MVP who started making universal applications before it was even a thing, will show you practical knowledge with a lot of demos. Come listen from the creator of the popular MVVM Light Toolkit how this powerful but simple library can be leveraged to help you target more users than you ever dreamed of!

Happy coding!

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook

Unity: Adding children to a GameObject in code and retrieving them

HoloLens, Technical stuff, Unity, Work

Update: The following feedback was pointed to me:

  • You should be careful when using GameObject.Find(…). First, it is bad for performance (note that in my code, I was using it in the Start method and then caching it. This is OK according to documentation, from a performance standpoint). Then, it relies on strings to pass the name of the object you are looking for. That’s not easily maintainable. Instead, it is better to set a public field in your script, and then assign the GameObject that you need in the Unity editor. To keep things simple, I won’t be doing this here but check the blog post here for more information
  • When you remove objects from a scene, you should always start by the last object and then go upwards.

End of update

When you work in the Unity editor, it is quite natural to use hierarchies of objects. For instance, you will have a table object and on this table object you want to place some cups objects, but if you move the table, you want the cups to move too. That’s quite a natural thing to do because it corresponds to the way that things are organized in “real life”. In fact, it even makes sense to have a hierarchy where the parent is an empty GameObject (which will be invisible), this way you can create logical groups of items.

For example, you can go in the Editor’s Hierarchy panel, create an empty GameObject (Right click on the panel and select Create Empty), and name it “Container”. Then you set a transform on the container, for example position = 0, 0, 2 meaning that the Container will be positioned 2 meters in front of the origin point.



Then you can right click on the Container and select 3D Object / Cube to add a cube to this parent. If you so, the new Cube will appear at the exact same position at the Container, as you would expect.



In code however, this is a little more tricky. This is where we realize that there is no true hierarchy of object in Unity but there is a hierarchy of transforms. Let see how to do that:

Creating new objects below the Container

Since we have an empty GameObject named Container in the scene, we can retrieve it in a script with the following code:

_container = GameObject.Find("Container");

The _container field, as you would expect, is of type GameObject. If you inspect it in the debugger, you will see that it is placed, as expected, at (0, 0, 2) (this is the transform.localPosition).

Now let’s create a new Cube and add it to the GameObject. Unfortunately, we notice that there is no Add or AddChild or similar method on the GameObject class. This is where we need to work with Transforms. The following code helps:

var newCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
newCube.transform.SetParent(_container.transform, true);
newCube.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);

In this snippet, we create a new Cube of 20 cm size, and we specify that the Cube’s transform’s parent is the Container’s transform (incidentally, Unity says that you should use SetParent and not the parent property directly, even though it can be set. Welcome to the ugly world of scripting ;). This will effectively create a hierarchy like we have in the editor. But there is a catch! If you run the code now, you will notice that the new Cube doesn’t appear, like you would expect, at (0, 0, 2) but it appears at (0, 0, 0). If you run this in a HoloLens, you will get pretty confused because (0, 0, 0) is probably going to be your head, and so the Cube is placed around your head and you won’t even see it until you move to a different location).

If you inspect the newCube in the debugger, you will see that its localPosition is set to (0, 0, –2). So it seems that Unity went out of this way to misunderstand what I was trying to do, and forced the newCube location to be at (0, 0, 0) globally, which means (0, 0, –2) relative to the parent. Ugh…

When reviewing the documentation, I found an overload of SetParent which takes a parameter named worldPositionStays of type bool. I thought that was promising, but setting this parameter to true didn’t change a thing. I also tried variations of the calls above. The newCube still appeared at (0, 0, 0). So to fix it, I forced the localPosition to be at (0, 0, 0) (relative to the Container). This way the global position of the Cube is (0, 0, 2).

newCube.transform.localPosition = new Vector3(0f, 0f, 0f);

This sounds unnecessarily complicated, so if I am doing things the wrong way, please add your knowledge in the comments, thanks!

Retrieving the children

Now how can we retrieve the children and iterate on them? For instance, this can be useful if you want to clean the scene by removing all the Cubes, but leaving the Container in place so the user can add more Cubes. Here too, we need to work with the transform hierarchy. Here is the code:

Note: For this simple demo I am not going to update the code BUT as was pointed in the comments, you should rather remove objects from the end of the hierarchy!

foreach (Transform t in _container.transform)
    var cube = t.gameObject;

In this code, we get the transform property of the Container and then we iterate through all its children. Then we retrieve the gameObject property of each transform, which corresponds to the Cube that we want to delete, which is done by calling the Destroy method.

Hopefully this quick tutorial will help you when you do this kind of things. Structure is very nice, but structuring a scene in code is a bit tricky. This should save you some time. Now again, if you see something that can be improved, don’t hesitate to point it out in the comments.

Happy coding!

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)

Share on Facebook

A world of devices – Upcoming talk

Personal, Technical stuff
No Comments

In September, I will give a special session in Amsterdam, at an event titled LevelUp Mobile. My talk is titled “A World of Devices”. Here is the abstract:

How do you feel when you forget your phone? If, like Laurent, you feel lost, you are probably also living in a world where devices are augmenting you and making you more connected, more efficient and more skilled (or is it addicted?). In this session, Laurent Bugnion, geek, developer and gadget addict will show you next generation devices and the collaboration between
them. From smartphones to smartwatches, from IOT and phablets to XBOX and Surface Hub, from Cortana to HoloLens, we live in a world of devices where software is coming out of the computer more and more. We’ll take a quick look at the past, a good look at the present and a glance at the future with lots of demos.

This talk is based on thoughts that I have had in my mind for many years already: Our devices, even the so-called smartphone (which, let’s face it, is not a phone but rather a pocket-sized computer with which you can, if you have to, place calls over the phone network) are augmenting us with superhuman abilities. How else could we know, with a precision of a meter or less, where we are positioned geographically? How else could we have access, from almost anywhere in the world (OK, that’s an exaggeration, but it is close enough for most of the civilized world) to a very significant portion of human knowledge? How else could we have access, anywhere and at any time, not only to enough movies, music and books to educate and entertain us multiple lifetimes. How else could we keep in touch 24/7 with our families and friends all over the world?

The smart device we have in the pocket is effectively turning us into cyborgs. Augmented humans. And this is only the beginning.


These days, we witness an incredible number of new devices, with new form factors. Maybe the most intriguing ones are the ones placed in the “wearable” category. The most common are smartwatches (which, like the smartphones, are much more than “just” watches). In their lowliest form, they need a connection to a smart device to be effective. But many are doing more than that. For instance the Microsoft Band 2 has a built in GPS and so it can record a run even without the help of a connected device. It also has a wealth of sensors that can be used to build mobile applications: Pressure sensor (so you can use it as a barometer / altimeter), heart rate, pedometer, distance, stairs, accelerometer and gyroscope (so you can use it to control 3D scenes or even physical objects), and even a UV-meter to tell you when you should put on solar cream.

We also saw the appearance, and then the quasi-disappearance, of connected glasses made by Google. It was certainly an interesting sociological experiment. Very soon we witnessed a lot of resistance in the population. Many felt aggressed, violated by the glass wearers (who were often referred to as “glassholes”). They felt that the wearers were displaying arrogance, and invading their private life, possibly recording video or taking pictures. The fact that the device had a low battery life and a low resolution was not playing a role in this concern. Neither was the fact that our lives are already recorded all the time, either by so-called security cameras, or by the constant picture-taking that everyone is doing these days. For some reason, the Google glasses were different and were perturbing the peace much more than any other device. This is (partially, to be completely fair) why they failed to gain traction, and why you don’t see them anymore these days. There are no doubts in my mind that more such devices will appear on the marketplace at some point in the future, although probably in a different form factor, less conspicuous and closer to normal glasses. There are already amazing devices available such as this model which allows an app to inform a person with impaired vision about what is happening around him/her. See Shaqib Shaikh’s great video shown at Microsoft Build this year!

This brings us, of course, to augmented and virtual reality. Even though these are not new domains, we are seeing this year a lot of interest and new devices. Oculus Rift is releasing its second iteration, HTC is selling its Vive device which is pretty great. Even on the low end of the marketplace we see devices like the Samsung Gear which takes advantage of smart devices and turns them into a poor man’s VR headset. And on the AR front we have of course Microsoft HoloLens, released to developers, an incredible device that not only places holograms in your everyday world, but also interacts with the real world and allows, for example, virtual objects to bounce off the real tables and the real walls, and for virtual characters to sit in real chairs.

And the most beautiful is when all these devices, from small to large, interact together and create a connected, augmented environment. This is the promise of Windows 10 and its universal applications, of cross-platform computing which has never been so promising, of wireless protocols that connect devices in very short or very large range, and allows them to collaborate.

At the LevelUp event, I will be talking about these concepts but also demonstrating some of the futuristic features that are already available to developers and to the public. I am really looking forward to have the occasion to share these thoughts with the audience, and demo how far we came with devices and their interactions.

Happy coding!

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook