Two ways to load external pictures in Unity3d

Source: Internet
Author: User

Like my blog Please remember my name: Qin Yuanpei , my blog address is: http://qinyuanpei.com
Reprint please indicate the source, this article author: Qin Yuanpei , this article source: http://blog.csdn.net/qinyuanpei/article/details/48262583

Hello friends, I am Qin Yuanpei, welcome to pay attention to my blog. Recently in the process of doing the project encountered a requirement: the player can be in the game during the real-time archiving, the archive process will save the current game progress, while the current game screen will be captured and loaded into the game archive interface. The next time you enter the game, the local archive image will be read and loaded into the game interface. This is a particularly common feature in stand-alone games, where there are two key points. The first is to capture the game screen, this problem can be in the "Unity3d game development screenshots Save wonderful moment" This article found the answer. The second is to load the image from the local, because it is guaranteed to be readable and writable, so the traditional resources.load () and Assetbundle methods are not able to achieve such a function. So how to load images from the outside into the game, that's what we're going to talk about today. Well, here are two ways to accomplish this. the popular www way

The popular www Way is loved, this is because this is the most familiar to us, we all know that through the WWW can be loaded from the web, pictures, audio and other forms of content, then through the WWW can load the local external (relative to the application) resources. The answer is yes, because WWW can support HTTP and file two protocols. We usually touch the WWW default refers to the HTTP protocol, now we say the file protocol, the protocol can be used to access local resources (absolute path). For example, we want to load the file D:\TestFile\pic001.png this file, then the corresponding C # script is:

Request www www www
= new www ("file://d:\\testfile\\pic001.png");
yield return www;        
if (www! = null && string. IsNullOrEmpty (www.error))
{
    //Get Texture
    Texture texture=www.texture;   
    More actions ...       
}

Notice that there is a yield return structure here, which means that the association is used here, so the price we need to pay is to use the Startcoroutine-related methods in the project to invoke these threads. While it is simple to use the Unity3d in the process, the simple code that makes us proud can become an endless abyss of pain if we casually use the process without paying attention to maintaining those processes. the timeless traditional IO approach

OK, here's a grand introduction of the immutable traditional IO way, this way I believe that we have not touched, so here will this method and share with you. Since it is the traditional IO way, it is nothing more than the processing of various IO streams. OK, let's take a look at the following code:

Create file read Stream
FileStream FileStream = new FileStream (screen, 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=800;
int height=640;
Texture2d texture = new Texture2d (width, height);
Texture. LoadImage (bytes);

You can see that when you use this method to read a picture file is mainly to convert the image file to byte[] array, and then use the Texture2d LoadImage method to convert to Unity3d texture2d. This method requires the size of the image to be passed in during the creation process, where we create a 800x640 image. After the blogger's research found that this way to load external images compared to the use of WWW loading external images more efficient, so if you meet similar needs, bloggers personally recommend this way to load.

So far we've solved how to load images from the outside into Unity3d, and now we're back to the beginning of the problem, we need to load them into the game interface after reading them externally. For example, when we use Ugui, the image control in Ugui needs a sprite as its fill, then we need to convert the texture to a sprite. Here's a simple example:

Using Unityengine;
Using System.Collections;
Using Unityengine.ui;

Using System.IO; public class Testloading:monobehaviour {//<summary>///Image control//</summary> private I

    Mage Image; void Start () {image = This.transform.Find ("image").

        Getcomponent<image> (); Bind different event This.transform.Find ("Loadbywww") for different buttons.
        Getcomponent<button> (). Onclick.addlistener (Delegate () {loadbywww ();

        ); This.transform.Find ("Loadbyio").
        Getcomponent<button> (). Onclick.addlistener (Delegate () {Loadbyio ();
    ); }///<summary>//IO Load///</summary> private void Loadbyio () {double STA
        Rttime = (double) time.time;
        Create file read stream FileStream FileStream = new FileStream ("D:\\test.jpg", 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 = 300;
        int height = 372;
        Texture2d texture = new Texture2d (width, height); Texture.

        LoadImage (bytes);  Create Sprite Sprite sprite = sprite.create (texture, new Rect (0, 0, Texture.width, texture.height), New Vector2 (0.5f,
        0.5f));

        Image.sprite = Sprite;
        Starttime= (double) time.time-starttime;
    Debug.Log ("Io Load Time:" + startTime); }///<summary>///for loading in WWW mode///</summary> private void Loadbywww () {Startcor
    Outine (Load ());
        } IEnumerator Load () {Double startTime = (double) time.time;
        Request www www www = new www ("file://d:\\test.jpg");        
        yield return www; if (www! = null && string. IsnullorempTy (Www.error)) {//Get texture texture2d texture=www.texture; Create Sprite Sprite sprite = sprite.create (texture, new Rect (0, 0, Texture.width, texture.height), new Vector2 (0
            .5f, 0.5f));

            Image.sprite = Sprite;
            StartTime = (double) time.time-starttime;
        Debug.Log ("WWW load time:" + startTime);
 }
    }
}

Now we run the program can be found in two ways can be loaded into the picture, in order to compare the two ways in the execution efficiency, we added the relevant code in the script, through the comparison can be found to use the IO method to load a 227k image takes 0s, Using the WWW mode to load requires 0.0185s, so the traditional IO approach is more efficient, and it is recommended that you use this approach whenever you encounter such problems. OK, today's content is this, welcome everyone in my blog message, welcome everyone concerned and support my blog, thank you.

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.