Forum Discussion

abdur.rahman.709771's avatar
abdur.rahman.709771
Honored Guest
2 years ago

Add Object Interactions During Runtime

Hello,

I'm trying to instantiate an object during runtime and need to add interactions to it. Specifically I want to add a mesh collider, rigiidbody, HandGrabInteractable, Grabbable, OneGrabFreeTransformer and TwoGrabFreeTransformer to the object. I can not create a prefab for the object as I'm importing it from a server and adding it to the scene during runtime. The issue I'm currently facing is that though I can add the components during runtime, how do I set the proper references in Grabbable for the transformers and in the HandGrabInteractable to the grabbable. I tried creating a prefab with all of the 5 components attached to it and add it as a child for the 3d object but for some reason this doesn't work.

3 Replies

  • Big_Flex's avatar
    Big_Flex
    Meta Employee

    Hi abdur.rahman.709771, have you tried using the "Inject" functions in the Interactor and Interactable scripts and their child classes? Those functions will let you specify components at runtime.  

  • Samer157's avatar
    Samer157
    Honored Guest

    Hi abdur.rahman.709771 , you need to use the Inject functions to assign the Rigidbody and Grabbable to the HandGrabInteractable component as Big_Flex mentioned. But the other thing that is needed is to register the interactable with the registry if you're doing this at runtime. For example:

    var grabbable = gameObject.AddComponent<Grabbable>();
    var rigidBody = gameObject.GetComponent<Rigidbody>(); // or add if you don't have it

    handGrabInteractable = gameObject.AddComponent<HandGrabInteractable>();
    handGrabInteractable.InjectRigidbody(rigidBody);
    handGrabInteractable.InjectOptionalPointableElement(grabbable);
    HandGrabInteractable.Registry.Register(handGrabInteractable); // This is the part that's essential to work at runtime.

    I had the same issue and was wondering why it won't work at runtime and had to dig to find this. Hope this helps!

    • moritz's avatar
      moritz
      Explorer

      Hey, thanks for your comment. Helped me out a great deal!

      For anybody looking for something similar for Injecting in grabbable scripts, this might help out:

      private ITransformer oneGrabTranslateTransformer;
      private Grabbable grabbable;
      
      void Awake()
      {
      oneGrabTranslateTransformer = grabbableObject.GetComponent<OneGrabTranslateTransformer>();
      grabbable = grabbableObject.GetComponent<Grabbable>();
      }
      
      private void InjectTranslateScript()
      {
      grabbable.InjectOptionalOneGrabTransformer(oneGrabTranslateTransformer);
      oneGrabTranslateTransformer.Initialize(grabbable);
      }

      Basically what I missed was the Initialize 🙂

      Hope that helps someone