Search code examples
unity-game-enginehololensmrtk

How to create OnPointerDownMixedRealityPointerEventData dynamycally in a cube?


I am working with MRTK 2.3.0 version, I have created a dragged cube when "event pointer down" creates a new gameobject cube, but the new cube has not event. I want to assign a event for move it. How could assign event by code?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Microsoft.MixedReality.Toolkit.Input;

    public class TouchableCube : MonoBehaviour, IMixedRealityPointerHandler
    {
        Color colorBlue = Color.blue;
        Renderer rend;

        public void OnPointerClicked(MixedRealityPointerEventData eventData)
        {
            rend.material.color = colorBlue;
        }


        public void OnPointerDown(MixedRealityPointerEventData eventData)
        {
            rend.material.color = Color.red;
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.position = new Vector3(0,0,2);

            cube.SetActive(true);


        }

        public void OnPointerDragged(MixedRealityPointerEventData eventData)
        {
            rend.material.color = Color.yellow;
            Vector3 v = new Vector3(
                               eventData.Pointer.Position.x,
                               eventData.Pointer.Position.y, 
                               eventData.Pointer.Position.z);
            rend.transform.position = v;   
        }

Solution

  • You can add a PointerHandler to your to and add listeners it. Here is how you would add a listener that changes a color of the cube, from your sample code:

            public void OnPointerDown(MixedRealityPointerEventData eventData)
            {
                rend.material.color = Color.red;
                GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cube.transform.position = new Vector3(0,0,2);
                var pointerHandler = target.AddComponent<PointerHandler>();
                pointerHandler.OnPointerDown.AddListener((e) => material.color = Color.green);
                pointerHandler.OnPointerUp.AddListener((e) => material.color = Color.magenta);
                cube.SetActive(true);
    
            }
    

    For more examples, see How to add near interactivity and Pointers.