- Home /
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?
Answer by Casiell · Apr 13, 2020 at 12:27 PM
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
Very interesting! Thank you, that was a great help and solved the problem. I've had to change my thinking a little with Unity.
For anyone else reading this, prefabs are a little tricky but definitely a much better solution that coding the whole thing. I created a GameObject Cube, added the Interactable script, and added the Prefab to a 'Resources' folder under Assets.
The following line was used to instantiate the object:
GameObject cuboid = Instantiate(Resources.Load("CuboidPrefab") as GameObject, new Vector3(0,0,0), Quaternion.identity);
And when viewing the object in the HoloLens app, it does indeed call the Interactable script as per the Prefab definition.
If it works in your case you can also just drag and drop prefabs to a field in your script.
So if you want script with Interactable class you declare the field as
public Interactable interactablePrefab;
Then you drag your prefab into this field in the inspector. To instantiate just do:
Interactable interactableInstance = Instantiate(interactablePrefab, new Vector3(0,0,0), Quaternion.identity);
This way is faster than loading from resources in terms of performance and also gives you the Interactable object outright, so you don't have to search for it with GetComponent. Doesn't work if your spawner class in not a $$anonymous$$onoBehaviour as you won't have access to inspector for this class