Home > database >  The functions of the buttons disappear when they appear
The functions of the buttons disappear when they appear

Time:10-13

I have prefabs of buttons, there is a script that generates them, as well as a script that contains the functions of the buttons. The generation script and the script with the functions are located on the object located on the scene (not the prefab).

How can I make the button functions be assigned before they appear on the scene and not disappear?

(I need to assign functions at the time of the prefab. They are generated randomly, and I need each button to correspond to the desired function in advance.)

My functions are pre-defined in the script. I also have an array of buttons into which I place the button prefabs. This function selects 3 random buttons from the array and puts them on the screen:

Blockquote

private void GenerateButtons()
    {
        int[] mixedArray = MixIntArray(_indexArray);

        int button1Index = mixedArray[0];
        int button2Index = mixedArray[1];
        int button3Index = mixedArray[2];

        Button button1 = Instantiate(_transformButtons[button1Index], transform.position   new Vector3(200, 0), transform.rotation, _border);
        Button button2 = Instantiate(_transformButtons[button2Index], transform.position, transform.rotation, _border);
        Button button3 = Instantiate(_transformButtons[button3Index], transform.position - new Vector3(200, 0), transform.rotation, _border);

        _createdButtons[0] = button1;
        _createdButtons[1] = button2;
        _createdButtons[2] = button3;
    }

MixIntArray - My function that randomly places numbers in an array.

I need the button already in the prefab to know what it should do. But the problem is that even if I put a function on it at this point, it will disappear when I create it.

CodePudding user response:

If you are talking about buttons used in UI system, you can instantiate them and follow with gettin the button component and set up desired function.

//Inside your spawning button function
Instantiate(buttonPrefab).GetComponent<Button>().onClick = yourOnClickEvent

CodePudding user response:

I found a solution.

If anyone encounters such a problem, try adding your prefabs to the scene and setting them up there. And then interact with other objects on the scene with the prefabs on the scene.

  • Related