Home > Mobile >  Unity - Assign Button in Scene to Prefab
Unity - Assign Button in Scene to Prefab

Time:12-23

I'm having trouble assigning two Buttons to the Prefab after it is instantiated. The buttons are in the scene and i don't know how to assign them. Drag and Drop doesn't work of course. I'm aware of that. When I make something like

btnnext = GameObject.Find("Next").GetComponent<Button>();

in the Start() function of the Prefabs script it doesn't work either.

Are there any other workarounds?

CodePudding user response:

By 'doesn't work either' you mean that btnnext is null or you mean that .GetComponent<Button>() throws an exception? The first case would mean the object named "Next" that was found doesn't have a Button component on it. You can check if you're expecting it to have the Button component or maybe something slightly different. You could also have multiple objects named "Next" and the one you're getting is not the one you expect to get. The second case would mean that your object is most likely inactive. Find(string) doesn't search within inactive objects.

That being said - Find(string) is not reliable in any capacity and I would advice to avoid it (it's also terribly slow). Instead I would create a script to be placed on the object with the button. Inside of that script in the Awake() method I would assign the instance of the Button component to some kind of a public static field, so the other script can later pick it up (if you are dealing with two buttons it might be a list or two separate fields. Depends on your case I guess).

CodePudding user response:

As @slowikowskiarkadiusz said GameObject.Find is not the best solution, because it's slow and error prone. But there is an easy solution.

On the script which is placed on the prefab make a public function, called AssignButton:

class ScriptOnPrefab : MonoBehaviour {
   public void AssignButton(Button button) {
      btnnext = button;
   }
}

In the script where you instantite the prefab, you then link the buttons and assign them:

var instance = Instantiate(prefab);
var scriptOnPrefab = instance.GetComponent<ScriptOnPrefab>();
scriptOnPrefab.AssignButton(button);

Note: For this to work that the ScriptOnPrefab has to be on the root of the prefab, note on child objects.

Note: prefab is linked as a GameObject.

Note: If you link the prefab as ScriptOnPrefab you can skip the GetComponent step and immediatelly call the Assign method.

  • Related