Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.XR.WSA.Persistence;
- using UnityEngine.XR.WSA;
- // Make sure you have the following Scripts in in your Scene: SpatialMappingObserver, SpatialMappingManager
- public class PersistantAnchorExample : MonoBehaviour
- {
- public WorldAnchorStore anchorStore;
- public GameObject AnchorRepresentation; // You have to set this to the Prefab you want
- void Start()
- {
- WorldAnchorStore.GetAsync(AnchorstoreReady); // On Start Load the Anchorstore
- }
- private GameObject InstantiateObject()
- {
- GameObject NewAnchorRepresentation = UnityEngine.Object.Instantiate(AnchorRepresentation);
- NewAnchorRepresentation.transform.position = Camera.main.transform.position + Camera.main.transform.forward;
- return NewAnchorRepresentation;
- }
- // Call this Function to Create a new Object with Anchor (For example from Voice Recognition)
- public void CreateObjectWithAnchor()
- {
- GameObject NewAnchorRepresentation = InstantiateObject();
- WorldAnchor newAnchor = NewAnchorRepresentation.AddComponent<WorldAnchor>();
- string AnchorID = "Anchor" + UnityEngine.Random.Range(10000, 99999).ToString(); //Generate a random name for the Anchor
- bool savedAnchor = false;
- try
- {
- savedAnchor = anchorStore.Save(AnchorID, newAnchor); // Now the Anchor is saved across multiple sessions
- }
- catch (System.Exception e)
- {
- Debug.Log(e);
- Debug.Log("Error Saving the Anchor");
- }
- if (!savedAnchor)
- {
- Debug.Log("Anchor failed to save to the store.");
- }
- }
- private void LoadAllAnchors()
- {
- if (anchorStore.anchorCount > 0)
- {
- string[] anchorIDs = anchorStore.GetAllIds();
- foreach (string anchorID in anchorIDs)
- {
- Debug.Log("Load " + anchorID);
- GameObject NewAnchorRepresentation = UnityEngine.Object.Instantiate(AnchorRepresentation);
- anchorStore.Load(anchorID, NewAnchorRepresentation); // This automatically sets the position of the object to the right position in the room
- }
- }
- else
- {
- Debug.Log("Anchor Store is empty");
- }
- }
- // Callback from WorldAnchorStore.GetAsync
- private void AnchorstoreReady(WorldAnchorStore store)
- {
- anchorStore = store;
- LoadAllAnchors();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement