How to add an Interactable script component to a GameObject programmatically

For a MS Hololens app, I’ve created a cube GameObject in Unity, with a simple Interactable script component that changes the cubes color depending on focus:

This is the full interactable component for the cube in Unity:

I’m now creating the cube objects through a script:

`

 void Awake() 
    { 
        // Create a cube at the origin 
        cube = GameObject.CreatePrimitive(PrimitiveType.Cube); 
        cube.name = "CUBE01"; 
        cube.transform.position = new Vector3(0.172f, -0.112f, 3.722f); 
        cube.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); 
    }

`
How do I even begin to add the same interactable script component in the code for the cube? Using an EventListener of some kind?

1 Answer

1

Use AddComponent method if you really want to create this cube through code.

But I would honestly recommend using prefabs for that, it’s the exact tool for the job