开发for循环代码,一次只实例化3个数组对象
本文关键字:一次 实例化 3个 对象 数组 循环 for 代码 开发 | 更新日期: 2023-09-27 18:05:01
所以我有一些代码来创建一个动态图库,创建一个文件位置的主数组,一个加载器协同程序,将图像加载到纹理和一个函数来实例化一个预制,该预制采用纹理,将其添加为精灵,然后相应地父预制。最后,for循环重复这个过程,直到我运行了整个文件数组,并用所有图像填充了我的图库。这适用于小型图库,但随着我的图库的增长,它可能变得笨拙,并开始占用大量内存。我的问题是我如何去修改这段代码,一次只加载3个图像(左,中,右)?我已经得到了我所有的图像在一个滚动容器,我想能够知道当图像滑离屏幕作为信号加载下一个(或上一个)。有没有人做过这个,不介意分享一点代码?
public Texture2D tex;
public string[] galleryImages;
GameObject galleryThumbHolder;
string[] arctopithecusImages;
string[] arctopithecusPNGImages;
string[] gulonImages;
string[] scythianWolfImages;
string[] simivulpaImages;
string[] succorathImages;
string[] tatusImages;
int currentIndex = 0;
// Create a master Array of all image files located in all Image locations
void Start()
{
// Build Gallery Arrays
arctopithecusImages = Directory.GetFiles(@"/Users/kenmarold/Screenshots/ARCTOPITHECUS/", "*.jpg");
arctopithecusPNGImages = Directory.GetFiles(@"/Users/kenmarold/Screenshots/ARCTOPITHECUS/", "*.png");
gulonImages = Directory.GetFiles(@"/Users/kenmarold/Screenshots/GULON/", "*.jpg");
scythianWolfImages = Directory.GetFiles(@"/Users/kenmarold/Screenshots/SCYTHIAN-WOLF/", "*.png");
simivulpaImages = Directory.GetFiles(@"/Users/kenmarold/Screenshots/SIMIVULPA/", "*.png");
succorathImages = Directory.GetFiles(@"/Users/kenmarold/Screenshots/SUCCORATH/", "*.png");
tatusImages = Directory.GetFiles(@"/Users/kenmarold/Screenshots/TATUS/", "*.png");
// Concatenate all Folder Array into single Array
galleryImages =
arctopithecusImages.Concat(arctopithecusPNGImages)
.Concat(gulonImages)
.Concat(scythianWolfImages)
.Concat(simivulpaImages)
.Concat(succorathImages)
.Concat(tatusImages)
.ToArray();
for(int i = 0; i < galleryImages.Length; i++)
{
StartCoroutine("loader", currentIndex);
currentIndex++;
}
}
IEnumerator loader(int indexNum)
{
WWW www = new WWW("file://" + galleryImages[indexNum]); // get the first file from disk
yield return www; // Wait unill its loaded
tex = new Texture2D(512,512); // create a new Texture2D
www.LoadImageIntoTexture(tex); // put the image file into the new Texture2D
createGalleryImages(tex);
}
public void createGalleryImages(Texture2D tex)
{
// Instantiate Gallery Thumb Prefab and Load in Sprite
//GameObject galleryThumb = Instantiate(Resources.Load("Prefabs/GalleryImageHolder")) as GameObject;
GameObject galleryThumb = Instantiate(GameObject.FindGameObjectWithTag("GalleryImgHolder")) as GameObject;
Image galleryImg = galleryThumb.GetComponent<Image>();
Rect rct = new Rect(0, 0, tex.width, tex.height); // Define Rect arg
Vector2 pvt = new Vector2(0.5f, 0.5f); // Define Pivot arg
galleryImg.sprite = Sprite.Create(tex, rct, pvt);
// Set Gallery Thumb Parent
galleryThumb.transform.SetParent(GameObject.FindGameObjectWithTag("GalleryThumbs").transform);
}
我曾经做过类似的事情,我实现它的方式是使用一个触发器,它检测进入的对象并获取分配给该对象的索引,在这里可以是数组中图像的索引,这样你就可以知道当前显示在中间的是哪个图像,如果用户向左或向右滚动,还可以加载另一个图像。