I have already get a NSData instance of an UIImage like this:
UIImage *myImage = [UIImage imageNamed:@"pic.png"];
NSData *imageData = UIImagePNGRepresentation(myImage);
Now I want to send the data to Unity and get the image.
Is there a possible solution to send “imageData” to Unity and use the function: Texture2D.LoadImage to get this image? I wonder whether the method “UnitySendMessage” in XCode can send this imageData to Unity?
Or is there any way to send an image from XCode’s UIImage to Unity?
Thanks for any idea.
I did something similar in an app I made where I let the user choose there own image for the players texture. So let me direct you to some helpful sources.
-
take the NSData
object that you have and save it. Your app has permission to write data to your game’s “Documents” folder. (According to the developer docs) The proper way of getting the documents path from XCode is to do the following:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
then append on your specific file name such "/MyImage.png". So you have the file directory and the data so save it (theres a method in `NSData` for writing to files), and you're ready for the next step.
-
In Unity, then you can read that file and load the image. For reading files, see @SpinalJack’s explanation here. Load the byte array using System.IO
into Unity.
-
Then the final step is the easiest. Use Texture2D.LoadImage() to load the image data into a texture.
EDIT: Just remembered, you can use the WWW
to load the bytes as well. Probably isn’t any faster than System.IO, but its easier. Just add file:
to the beginning of the asset path in Unity.