1
votes

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.

2
do you mean the function Instantiate() or the colloquial 'set values and make ready'? I ask because from what is written here it's a little confusing... you are trying to create something that already exists? =s ps [unity3d] tag on here not [unity] :)Lefty
Hi, yes, I mean instantiate. The prefab already exists, but it does not exist in the scene itself. I am trying to get the canvas into the scene using the DialogueController script, which is on the canvas itself.Archetype90

2 Answers

1
votes

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")); 
} 
0
votes

From the comments, it seems like you need an initial "seed" instance of that Canvas which contains your script to instantiate more copies if you need. Part 2 is most common for your needs

The easiest way is to have one instance of said canvas already in the scene. You could have the drawable/visible canvas part "disabled" by unticking the little checkbox in the inspector, and then have it enable itself in a function of a script on the GameObject...

void Start ()
{
    thisCanvas = GetComponent<Canvas>();
    thisCanvas.enabled = true;
}

of course, another way would just be to instantiate one copy from another script which you already have in the scene - classic case: Create a BLANK GameObject in your scene (CTRL+Shift+N), [F2] rename it "GameManager" (SOME unity functions still bug out when there are spaces in GameObject names BTW) and then attach a new script called GameManager. This script is basically just here to make sure the right scenes load, and instantiate certain prefabs, make network connections, set player variables that you haven't done from the editor etc etc so:

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour
{

    public GameObject myObject;

    void Start ()
    {
        Instantiate(myObject, transform.position, transform.rotation);
    }

}

now drag+drop your "prefab" which you want to instantiate into the slot on your "GameManager" in the inspector. Note that it doesn't have to be when the game starts, another example is the GameManager script having a function listening for whenever a login is needed, and at that time - it instantiates your login dialog.