Unity Editor automatically generates materials and dynamically loads resources

Source: Internet
Author: User

The last two days in a project, and then there are more than 60 materials, but also all the material to create the ball, almost people are wasted, and then go to the manual on the code can be automatically generated material ball. And then automatically generate the material ball in the process I also want to give the material ball a default diffuse map, the map is downloaded from the Internet, stepping on the countless pits after the finally fix.
Direct Code Placement

   Use the this for initialization void Start () {Startcoroutine (Downloadfiles ()); } public IEnumerator Downloadfiles () {//use unitywebrequest to download texture using (unitywebrequest www = UnityWeb
        Request.gettexture ("Http://pic1.16pic.com/00/04/57/16pic_457578_b.jpg")) {yield return www.Send ();
        if (www.isError) {Debug.Log (www.error);
            } else {Debug.Log (www.downloadHandler.data.Length);

                try {FileInfo fi = new FileInfo ("Assets/pictures/image.png"); if (!fi. Exists) {//If the file does not exist, create the file Stream OutStream = fi.
                    Create ();
                    Store the downloaded data to a local file Outstream.write (www.downloadHandler.data, 0, www.downloadHandler.data.Length);
                    Close file stream Outstream.close (); Resource refresh this sentence must be added otherwise, although the file is under the folder, the textis not added to the project Assetdatabase.refresh (); }//gets to the texture file Texture mytexture = Assetdatabase.loadassetatpath ("Assets/pic

                    Tures/image.png ", typeof (Texture2d)) as texture2d;

                Debug.Log ("Download succeeded");
                The following is the automatic conversion of the image to create material ball//wear piece material ball Material Material = new Material (Shader.find ("standard"));
            Assign the previously saved texture to the material ball material.maintexture = mytexture;
                Save Material Ball Assetdatabase.createasset (material, "/material/image.mat");
            Assetdatabase.refresh ();
                } catch (Exception e) {Debug.Log (e.message);
            Debug.Log ("Download Failed"); }
            }

        }
    }

Unitywebrequest This class is a package of unity to www. It provides a series of methods. Use the Unitywebrequest method for network requests. Then get the returned data. Finally, create a file and put it in the folder. Assetdatabase.refresh (); This sentence must be added, does not add to the editor does not change the map, then the last created material ball will not have a default map. Finally, use the Assetdatabase.createasset method to create a material ball.
When you refresh the import map, the default map type is texture2d type, if you want to modify the type, then add a file under the Editor folder, add the following code:

public class Transimagetype:assetpostprocessor
{

    void onpreprocesstexture ()
    {

        Debug.Log (" Onpreprocesstexture ");
        Auto set type;  
        Textureimporter Textureimporter = (textureimporter) assetimporter;
        Textureimporter.texturetype = Textureimportertype.image;

    }
}

Textureimportertype corresponding type types can be queried on the web. The method above modifies unitywebrequest.gettexture to Unitywebrequest.get and can add any new file in the editor state. However, you need to ensure that the folder must exist and that there are no errors that would report the path not found.

This method can only be run in editor mode, and if the program is already published, a new method is required if you use external resources. After you have browsed through n multiple resources online, where
http://www.cnblogs.com/murongxiaopifu/p/4199541.html?utm_source=tuicool&utm_medium= Referral
This article has given me a lot of help, then I modified the code, there are two ways to read the image externally, one is to use the WWW method to load, and the other is to use the stream method to load the file, Unity provides an interface using external texture resources, To download the resources to the destination folder first, the code is as follows:

    Public IEnumerator Downloadfiles () {//use unitywebrequest to download texture using (unitywebrequest www = UnityWeb
        Request.gettexture ("Http://pic1.16pic.com/00/04/57/16pic_457578_b.jpg")) {yield return www.Send ();
        if (www.isError) {Debug.Log (www.error);
            } else {Debug.Log (www.downloadHandler.data.Length);
                try {FileInfo fi = new FileInfo (application.persistentdatapath+ "/image.png"); if (!fi. Exists) {//If the file does not exist, create the file Stream OutStream = fi.
                    Create ();
                    Store the downloaded data to a local file Outstream.write (www.downloadHandler.data, 0, www.downloadHandler.data.Length);
                    Close file stream Outstream.close (); Resource refresh this sentence must be added otherwise, although the file is under the folder, the file has not been added to project engineering} spath = "file:///" + application. PersIstentdatapath + "/image.png";
                    Debug.Log ("Download succeeded");

            Print (spath);
                } catch (Exception e) {Debug.Log (e.message);
            Debug.Log ("Download Failed"); }
            }

        }
    }

After the picture has been downloaded successfully, there are two first raw IO get textures loaded, the code is as follows:

<summary>
    ///IO Load///</summary> private void Loadtexturebyio ()
    {
        double StartTime = (double) time.time;
        Create file read Stream
        FileStream FileStream = new FileStream (Application.persistentdatapath + "/image.png", FileMode.Open, FileAccess.Read);
        Filestream.seek (0, seekorigin.begin);
        Create file length buffer
        byte[] bytes = new Byte[filestream.length];
        Read file
        filestream.read (bytes, 0, (int) filestream.length);
        Release file read stream
        filestream.close ();
        Filestream.dispose ();
        FileStream = null;

        Create texture
        int width = +;
        int height = 372;
        Texture2d texture = new Texture2d (width, height);
        Texture. LoadImage (bytes);
       The following code is used to do any function you want to implement ...
    }

Another way to load is to use Unity's method to get the texture, the code is as follows:

Private IEnumerator loadtexturebywww () {
        using (www w = new www ("file:///" + Application.persistentdatapath + "/image. PNG ")) 
        {
            yield return w;
            Texture2d tex = w.texture;
            The following code uses textures to do any function you want to implement ...
        }
    }

The above code has a need to pay special attention to the point is that the file must be followed by three/, if you write two/, then the WWW in the reading of local resources when the path will be a problem, the drive letter will be lost, because see Unity source code, so I do not know how to deal with the bottom, here is a big pit, You can then use Tex to perform the functions you need to implement. Example demo will be available after the free collation and update. Convenient for later inspection.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.