欢迎光临散文网 会员登陆 & 注册

Up自制Unity预制脚本pictureSpawner.cs

2023-04-04 07:10 作者:拥抱大自然  | 我要投稿

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using System.IO;


public class pictureSpawner : MonoBehaviour

{

    public string mainFolder;

    string[] folders;     

    string folderName;


    public FileInfo[] fileNames;

    DirectoryInfo folder;


    float gap = 1.0f;

    public float deltaGap=0.1f;


    public float scale = 1.5f;


    FileStream fileStream;

    Texture2D texture;

    byte[] bytes;


    GameObject pointer;

    public GameObject pictureBoard;


    // Start is called before the first frame update

    void Start()

    {

        folders=Directory.GetDirectories(mainFolder, "*", SearchOption.AllDirectories);


        SpawnFolders(mainFolder);


        foreach(string i in folders)

        {

            SpawnFolders(i);

        }     

    }


    // Update is called once per frame

    void Update()

    {

        

    }


    void LoadFile(string tempInput)

    {

        fileStream = new FileStream(tempInput, FileMode.Open, FileAccess.Read);

        fileStream.Seek(0, SeekOrigin.Begin);

        bytes = new byte[fileStream.Length];

        fileStream.Read(bytes, 0, (int)fileStream.Length);

        fileStream.Close();


        texture = new Texture2D(100, 100, TextureFormat.ETC2_RGB , false);

        //此处设置优化格式为ETC2_RGB,不一定是最优化的格式,后期有机会找个更好的。


        texture.LoadImage(bytes);


        bytes = null;

    }


    

    void PictureBoardSpawn(string tempName)

    {        

        pointer = Instantiate(pictureBoard, new Vector3(transform.position.x+gap, transform.position.y+1, transform.position.z), transform.rotation);

        pointer.transform.localScale = new Vector3(texture.width * 0.001f*scale, 1, texture.height * 0.001f*scale);


        pointer.transform.name = tempName;


        gap += deltaGap;


        //pointer.GetComponent<Renderer>().material.SetTexture("_MainTex", texture);

        //配合无光照模式用。也就是图片不受光照影响。


        pointer.GetComponent<Renderer>().material.mainTexture = texture;


        texture = null;   


        pointer.transform.localScale = new Vector3(pointer.transform.localScale.x * 0.1f, 1, pointer.transform.localScale.z * 0.1f);


        pointer.transform.parent = this.transform;


    }



    void SpawnFolders(string tempFolderName)

    {

        folder = new DirectoryInfo(tempFolderName);


        fileNames = folder.GetFiles("*");


        if (fileNames.Length > 0)

        {

            foreach (FileInfo temp in fileNames)

            {

                LoadFile(temp.ToString());


                PictureBoardSpawn(temp.ToString());

            }


            fileStream.Dispose();

        }

    }


}


Up自制Unity预制脚本pictureSpawner.cs的评论 (共 条)

分享到微博请遵守国家法律