Search code examples
c#unity-game-engineaugmented-realitymrtk

How to turn on a prefab with code in C# and unity


I am new to C# and I am working on an AR project where I am showing directions to a section of books in a library. I have a basic scene set up where the user clicks on a button and something happens. I am using the Mixed Reality Tool Kit's directional indicator. I created 4 game objects that represent different subjects and are placed at different points in space in the scene. I have a directional indicator for each of those game objects and those directional indicators are prefabs. They are an arrow that points to that game object, so what I am trying to do is have them turned off and when the user clicks the button, it turns them on.


Solution

  • Prefabs are just files that contain GameObject, they aren't directly connected to the scene. If you want to create new GameObject from Prefab in runtime you can Instantiate it, and then keep reference to this new GameObject.

    You also can check similar question, maybe it will help.

    Code example

    class SomeClass: MonoBehaviour
    {
        private GameObject newGameObject;
        ...
        public void InstantiatePrefab(GameObject prefab)
        {
            newGameObject = Instantiate(prefab, ...);
        }    
    
        public void SetGameObjectState(bool state)
        {
            newGameObject.SetActive(state);
        }
    }