简体   繁体   English

单击按钮时,生成GameObject并从纹理数组设置其图像-Unity 4.6(使用uGUI)

[英]Generate GameObjects and set their image from an Array of Textures when a button is clicked - Unity 4.6 (using uGUI)

I'm having a lot of trouble trying to develop a loader that when a button gets clicked it takes an array of textures and populates them into a grid layout (and when another button is clicked it removes the current textures and replaces them with a new array of textures). 我在尝试开发一个加载器时遇到很多麻烦,当单击一个按钮时,加载器需要一系列纹理并将其填充到网格布局中(单击另一个按钮时,它将删除当前纹理并用新的纹理替换它们阵列的纹理)。 I have the grid layout portion of the UI fully sorted and the Texture arrays are generated, I just need help with: 我已经对UI的网格布局部分进行了充分排序,并生成了Texture数组,我只需要以下方面的帮助:

  1. Assigning each texture to an Image component of individually generated GameObjects. 将每个纹理分配给单独生成的GameObjects的Image组件。
  2. Populating the grid layout it with those GameObjects. 用那些GameObjects填充网格布局。

Could anyone share some code insight or a snippet that might do the trick? 任何人都可以分享一些可以解决问题的代码见解或摘要吗?

First create script inside of your Canvas or create empty GameObject with script. 首先在Canvas内创建脚本或使用脚本创建空的GameObject

Create public variables: 创建公共变量:

public Sprite[] mySprites;
public GameObject myGridLayoutGameObject;
public GameObject myGridElement;

In mySprites assign all your sprites via editor. mySprites通过编辑器分配所有精灵。

For myGridLayoutGameObject assign your GUI GameObject with GridLayoutGroup . 对于myGridLayoutGameObject您的GUI myGridLayoutGameObject分配GridLayoutGroup

For myGridElement , you must create prototype GUI object with Image and place it outside of your canvas, in order to make it not visible for your camera. 对于myGridElement ,您必须使用Image创建原型GUI对象,并将其放置在画布之外,以使其在相机中不可见。 Assign it to your scripts variable. 将其分配给您的脚本变量。

Then you can create some method: 然后,您可以创建一些方法:

public void fillGrid() {
    foreach (Sprite sprite in mySprites) {
        GameObject instance = Instantiate(myGridElement, myGridElement.transform.position, myGridElement.transform.rotation) as GameObject;
        instance.GetComponent<Image>().sprite = sprite;
        instance.transform.SetParent(myGridLayoutGameObject.transform);
    }
}

It will automatically place all your objects inside grid, depending on your settings. 它将根据您的设置自动将所有对象放置在网格内。 Do not forget to add using UnityEngine.UI; 不要忘记使用UnityEngine.UI添加 on head of your script. 在脚本的头上。

Also, I have written this code for Unity 5. Unity 4.6 may have some differencies on GUI elements. 另外,我已经为Unity 5编写了这段代码。Unity4.6在GUI元素上可能会有一些差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM