World anchor in Unity

Namespace: UnityEngine.VR.WSA

Type: WorldAnchor

WorldAnchors provide a way for an application to specify a position and rotation in the real world and relate that position and rotation to the application’s frame of reference. This can provide additional stability for GameObjects and provides a mechanism for preserving real world positions for future instances of the application. You can learn more about the WorldAnchor on the spatial anchors topic.

Adding a World Anchor

To add a world anchor, call AddComponent<WorldAnchor>() on the game object with the transform you want to anchor in the real world.

WorldAnchor anchor = gameObject.AddComponent<WorldAnchor>();

Removing a World Anchor

If you no longer want the GameObject locked to a physical world location and don't intend on moving it this frame, then you can just call Destroy on the World Anchor component.


If you want to move the GameObject this frame, you need to call DestroyImmediate instead.


Moving a World Anchored GameObject

GameObject's cannot be moved while a World Anchor is on it. If you need to move the GameObject this frame, you need to:

  1. DestroyImmedaite the World Anchor component
  2. Move the GameObject
  3. Add a new World Anchor component to the GameObject.
gameObject.transform.position = new Vector3(0, 0, 2);
WorldAnchor anchor = gameObject.AddComponent<WorldAnchor>();

Handling Locatability Changes

A WorldAnchor may not be locatable in the physical world at a point in time. If that occurs, Unity will not be updating the transform of the anchored object. This also can change while an app is running. Failure to handle the change in locatability will cause the object to not appear in the correct physical location in the world.

To be notified about locatability changes:

  1. Subscribe to the OnTrackingChanged event
  2. Handle the event

Subscribe to the OnTrackingChanged event

This event will be called whenever the underlying spatial anchor changes between a state of being locatable vs. not being locatable.

anchor.OnTrackingChanged += Anchor_OnTrackingChanged;

Handling the OnTrackingChanged event

Then handle the event:

private void Anchor_OnTrackingChanged(WorldAnchor self, bool located)
       // This simply activates/deactivates this object and all children when tracking changes

Set initial state explicitly

Sometimes anchors are located immediately. In this case, this isLocated property of the anchor will be set to true when AddComponent<WorldAnchor>() returns. As a result, the OnTrackingChanged event will not be triggered. A clean pattern would be to call your OnTrackingChanged handler with the initial IsLocated state after attaching an anchor.

Anchor_OnTrackingChanged(anchor, anchor.isLocated);

See Also