Search code examples
c#unity-game-engineinstantiationgameobject

Instantiate gameobject from a script that is on that gameobject


I have a script called DialogueController, which is attached to a canvas. I would like to instantiate that canvas from the DialogueController script. Whenever I attempt to do this, all of the public objects that were assigned to the canvas through the Unity editor are set to null (including the canvas itself, which is what I am trying to instantiate).

Is there a simple way to do this? I have an alternative solution, but being able to do this would keep my code slightly more compartmentalized.


Solution

  • You could initialize these variables from the script itself, using the resources folders (and the Resources.Load() method). Something like that:

    //The canvas is at the path "Assets/Resources/canvas".
    
    function Start () { 
        your_canvas = Instantiate(Resources.Load("canvas")); 
    }