如何正确通过Unity C#中的脚本实例化预制?

发布于 2025-02-12 02:39:20 字数 761 浏览 2 评论 0原文

我正在通过统一脚本实例化预制。这是一种工作,但实际上并非如此。 预制措施以正确的名称出现在层次结构中,但在场景中,看不到。 我已经浏览了我看到的每个问题,这是相似的,但不幸的是,我无法解决问题。我尝试更改脚本中的向量和预制本身的位置。 感谢任何帮助。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烏雲後面有陽光 2025-02-19 02:39:20

看来您正在尝试实例化应该在世界空间中canvas(Unity UI系统)中使用的对象。

canvas root对象上的组件需要渲染所有子UI元素,例如buttontextimage> 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 like Button, 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 the Canvas component attached to any of its parents.

Also, make sure that the EventSystem component is present at the scene to make Buttons work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文