如何正确通过Unity C#中的脚本实例化预制?
我正在通过统一脚本实例化预制。这是一种工作,但实际上并非如此。 预制措施以正确的名称出现在层次结构中,但在场景中,看不到。 我已经浏览了我看到的每个问题,这是相似的,但不幸的是,我无法解决问题。我尝试更改脚本中的向量和预制本身的位置。 感谢任何帮助。
public class ButtonControler : MonoBehaviour
[SerializeField] private Button[] buttonsList;
public GameObject button;
public void Awake()
{
InitializeButtons();
}
private void InitializeButtons()
{
for (int i = 0; i < CsvManagerDownloader.experiments.Count; i++)
{
string buttontext = "Experiment" + i;
GameObject newButton = Instantiate(button, new Vector3(0, 0, 0), Quaternion.identity);
newButton.GetComponentInChildren<Text>().text = buttontext;
}
(此脚本只能在 csvmanagerdownloader 之后调用,因为从该脚本收集按钮的数量。)
I am instantiating a prefab thru a script in Unity. It's kind of working but not really.
The prefab shows up in the hierarchy with the correct name but in the scene, it cannot be seen.
I have looked through every question I saw, that was similar but unfortunately, I couldn't solve my problem. I tried changing the Vector in the script and the position of the prefab itself.
I appreciate any help.
public class ButtonControler : MonoBehaviour
[SerializeField] private Button[] buttonsList;
public GameObject button;
public void Awake()
{
InitializeButtons();
}
private void InitializeButtons()
{
for (int i = 0; i < CsvManagerDownloader.experiments.Count; i++)
{
string buttontext = "Experiment" + i;
GameObject newButton = Instantiate(button, new Vector3(0, 0, 0), Quaternion.identity);
newButton.GetComponentInChildren<Text>().text = buttontext;
}
(This script can only be called after CSVManagerDownloader, since the number of buttons is gathered from that script.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您正在尝试实例化应该在世界空间中
canvas
(Unity UI系统)中使用的对象。canvas
root对象上的组件需要渲染所有子UI元素,例如button
,text
,image> image
等。父母。
另外,请确保场景中存在
Eventsystem
组件以制作按钮
工作。It seems that you are trying to instantiate an object that is supposed to be used inside
Canvas
(unity UI system) in the world space.Canvas
component on the root object is needed to render all child UI elements likeButton
,Text
,Image
, etc.So, if you want your instantiated object with the
Button
component to be visible, make sure, that you place it in the hierarchy with theCanvas
component attached to any of its parents.Also, make sure that the
EventSystem
component is present at the scene to makeButtons
work.