Post

How to save object position on HoloLens

Saving positions of holograms is most of the time a must for a usable application. It sounds complicated but actually simpler than one would think. Besides a HoloLens development environment you need to;

  1. Read “Spatial anchors” section from Microsoft’s mixed reality guide to understand what’s going on behind the scenes.
  2. Add HoloToolkit-Unity or WorldAnchorManager script and it’s dependencies to your project.

When you got everything ready, add WorldAnchorManager to your scene. It doesn’t actually matter much where to but to keep things tidy, it’s better to add it under a new game object called “Anchor Manager”.

After WorldAnchorManager is added all you have to do is following code from a script that attached to your gameObject;

1
WorldAnchorManager.Instance.AttachAnchor(gameObject, anchorName);

And if you don’t want to save the position of that gameObject anymore, you should call;

1
WorldAnchorManager.Instance.RemoveAnchor(gameObject);

If you try this now, you will realize you can’t move your objects anymore. Weird, uh? Well, since you associated certain position with your object, HoloLens assures that it stays there. To avoid this, remove anchor before moving the object, and add it back with the same anchor name afterwards. For example, if you are using HandDraggable script from HoloToolkit-Unity you can do it like this;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void Start () {
    // Adding anchor initially
    WorldAnchorManager.Instance.AttachAnchor(gameObject, anchorName);

    gameObject.GetComponent<HandDraggable>().StartedDragging += () =>
    {
        // Removing anchor temporary when dragging started
        WorldAnchorManager.Instance.RemoveAnchor(gameObject);
    };
    gameObject.GetComponent<HandDraggable>().StoppedDragging += () =>
    {
        // Adding back with the same name when dragging ended
        WorldAnchorManager.Instance.AttachAnchor(gameObject, anchorName);
    };
}

Also don’t forget to check best practices document at Windows Dev Center

This post is licensed under CC BY 4.0 by the author.