0
votes

I am trying to create button in C# code using an existing Prefab. All I found on the website was something like

public GameObject a;
public RectTransform ParentPanel;
void Start()
{
    for (int i = 0; i < 5; i++)
    {
        GameObject goButton = (GameObject)Instantiate(a); /error
        goButton.transform.SetParent(ParentPanel, false);
        goButton.transform.localScale = new Vector3(1, 1, 1);
            Button tempButton = goButton.GetComponent<Button>();
    }
}

In Unity project I have Prefab called "ButtonPrefab" where I put Button Object. There is an error in below line

UnassignedReferenceException: The variable a of NewBehaviourScript has not been assigned. You probably need to assign the a variable of the NewBehaviourScript script in the inspector.

I am new to Unity. How is it come that not assigned var a can give me button using Instantiate()? And why do I have this error?

1
if it's just for debug you can probably get away with this docs.unity3d.com/ScriptReference/GUI.Button.htmlslf
Do you drag and drob GameObject a from editor?Barış Çırıka

1 Answers

0
votes

You can instantiate prefabs very easily from within a Resources folder. Make a new folder within your project's Assets folder called Resources. It must be named Resources for this to work properly. Then you can make your button like this:

GameObject button = Instantiate(Resources.Load("myButton", typeof(GameObject))) as GameObject;

Assuming your prefab is named "myButton."