按钮的功能在出现时消失



我有按钮的预制件,有一个生成它们的脚本,还有一个包含按钮功能的脚本。生成脚本和具有功能的脚本位于场景中的对象上(而不是预制件(。

如何使按钮功能在出现在场景中而不消失之前进行分配?

(我需要在预制时分配功能。它们是随机生成的,我需要每个按钮预先对应所需的功能。(

我的函数是在脚本中预定义的。我还有一个按钮阵列,我把按钮预制件放在其中。该功能从阵列中随机选择3个按钮,并将它们放在屏幕上:

区块报价

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-我的函数,在数组中随机放置数字。

我需要已经在预制中的按钮来知道它应该做什么。但问题是,即使我在这一点上放了一个功能,当我创建它时,它也会消失。

如果您谈论的是UI系统中使用的按钮,您可以实例化它们,然后在按钮组件中使用gettin并设置所需的功能。

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

我找到了一个解决方案

如果有人遇到这样的问题,请尝试将预制件添加到场景中并在那里进行设置。然后使用场景中的预制件与场景中的其他对象进行交互。

最新更新