Unity - Share/Post Image To Facebook, Whatsapp, Twitter etc on Android


Letting users share your game from the game itself is a must have feature in any game. Even more important is the ability to share images from your game to the social media like facebook, whatsapp, twitter etc., say, on completing a level you can load a particular image and allow users to share that image with their friends saying he has cleared so and so level.

Follow the step below to implement this feature in your game:

1. Create a folder named Resources, if you don't have one already.

2. Change the extension of the images from .png/.jpg or .bytes and place them in your Resources folder just created.
ex: If you have an image named MyPic.png, once you complete the above step, it should be Mypic.bytes

3. Create a new C# script named ShareImage and paste the below code into it.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;

public class ShareImage : MonoBehaviour {
 
 private bool isProcessing = false;

 private string shareText  = "Which Hollywood Movie does this PICTURE represent?\n";
 private string gameLink = "Download the game on play store at "+"\nhttps://play.google.com/store/apps/details?id=com.TGC.guessthemovie&pcampaignid=GPC_shareGame";
 private string subject = "Rebus Guess The Movie Game";
 private string imageName = "your image name"; // without the extension, for iinstance, MyPic 
 public void shareImage(){

  if(!isProcessing)
   StartCoroutine( ShareScreenshot() );
 
 }

 private IEnumerator ShareScreenshot(){
  isProcessing = true;
  yield return new WaitForEndOfFrame();
 
  Texture2D screenTexture = new Texture2D(1080, 1080,TextureFormat.RGB24,true);
  screenTexture.Apply();

  byte[] dataToSave = Resources.Load<TextAsset>(imageName).bytes;
  
  string destination = Path.Combine(Application.persistentDataPath,System.DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + ".png");
  Debug.Log(destination);
  File.WriteAllBytes(destination, dataToSave);

  if(!Application.isEditor)
  {
   
   AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
   AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent");
   intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStaticlt;string>("ACTION_SEND"));
   AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri");
   AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("parse","file://" + destination);
   intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"), uriObject);
   intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), shareText + gameLink);
   intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_SUBJECT"), subject);
   intentObject.Call<AndroidJavaObject>("setType", "image/jpeg");
   AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
   AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
   
   currentActivity.Call("startActivity", intentObject);
   
  }
  
  isProcessing = false;

 }
 
}

Save the script and return to unity.

4. Call the shareImage() method on click of a button.

5. Build and Run the game on your Android device to witness the magic right before your eyes.

See you around.
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
    Blogger
    Facebook

63 comments:

  1. Para min funcionou certinho , adicionando as alteracoes deste post, voce esta de parabens
    http://answers.unity3d.com/questions/1035384/unity-android-image-share-to-facebook-fails.html

    ReplyDelete
  2. a litle TYPO in line 39 [ intentClass.GetStaticlt;string> ] it should be...
    intentClass.GetStatic

    ReplyDelete
  3. Thanks very much Working ....
    add write files permission in android manifest.

    ReplyDelete
  4. its not working, the text is shown very well but the image appears in "white". So you intent upload the image on the platforms and all of them triggers errors :/

    ReplyDelete
  5. App restarts when we return after sharing. I have posted my question in detail here:

    http://forum.unity3d.com/threads/social-sharing-app-restarts-on-sharing.392186/

    Help out.

    ReplyDelete
  6. It's not working...

    NullReferenceException: Object reference not set to an instance of an object
    Share+c__Iterator0.MoveNext () (at Assets/Share.cs:29)

    ReplyDelete
  7. Cara muito legal, mas e o Whatsapp?

    ReplyDelete
  8. NullReferenceException: Object reference not set to an instance of an object
    ShareImage+c__Iterator0.MoveNext () (at Assets/Scripts/ShareImage.cs:29)

    ReplyDelete
  9. Hi is it possible to sharing video to instagram same way?

    ReplyDelete
  10. Using this we can integrate arbitrary JSON data such as social data feeds from Twitter, Facebook, Google, and aggregators like Datasift among many others.

    http://buyfblikescheap.com/buying-real-facebook-likes/

    ReplyDelete
  11. I want to say thanks to you. I have bookmark your site for future updates.
    melancong

    ReplyDelete
  12. How do we make the share window look like Crossy Road. I don't want the "Just once" and "Always" options.

    ReplyDelete
  13. how to convert image from .png to .bytes extenstion?

    ReplyDelete
  14. Line 39 giving error kindly help !!
    intentClass.GetStaticlt;string>("ACTION_SEND"));

    ReplyDelete
    Replies
    1. ("setAction", intentClass.GetStaticlt("ACTION_SEND"));

      Delete
    2. This comment has been removed by the author.

      Delete
    3. intentClass.GetStatic ("ACTION_SEND"));

      Delete
  15. This comment has been removed by the author.

    ReplyDelete
  16. how to share link on facebook
    help me

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. how to unity ios share image text & link on whatsapp?

    ReplyDelete
  19. I got this error and i dont know how to fix it.
    Please help!
    NullReferenceException: Object reference not set to an instance of an object
    ShareImage+c__Iterator0.MoveNext () (at Assets/Sript/ShareImage.cs:31)
    UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

    ReplyDelete
  20. line 39 error fix:
    intentObject.Call("setAction", intentClass.GetStatic("ACTION_SEND"));

    ReplyDelete
  21. WhatsApp alerts you when a user is online and their last seen time. With BBM, you are not furnished such information but you will still know when another is available or busy according to their current status. Picup line

    ReplyDelete
  22. Line 39 giving error kindly help !!
    intentClass.GetStaticlt;string>("ACTION_SEND"));
    Boş can i fix it

    ReplyDelete
  23. WORKING CODE!

    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    using System.IO;

    public class ShareImage : MonoBehaviour
    {

    private bool isProcessing = false;

    private string shareText = "Which Hollywood Movie does this PICTURE represent?\n";
    private string gameLink = "Download the game on play store at " + "\nhttps://play.google.com/store/apps/details?id=com.TGC.guessthemovie&pcampaignid=GPC_shareGame";
    private string subject = "Rebus Guess The Movie Game";
    private string imageName = "your image name"; // without the extension, for iinstance, MyPic
    public void shareImage()
    {

    if (!isProcessing)
    StartCoroutine(ShareScreenshot());

    }

    private IEnumerator ShareScreenshot()
    {
    isProcessing = true;
    yield return new WaitForEndOfFrame();

    Texture2D screenTexture = new Texture2D(1080, 1080, TextureFormat.RGB24, true);
    screenTexture.Apply();

    byte[] dataToSave = Resources.Load(imageName).bytes;

    string destination = Path.Combine(Application.persistentDataPath, System.DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + ".png");
    Debug.Log(destination);
    File.WriteAllBytes(destination, dataToSave);

    if (!Application.isEditor)
    {

    AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
    AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent");
    intentObject.Call("setAction", intentClass.GetStatic ("ACTION_SEND"));
    AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri");
    AndroidJavaObject uriObject = uriClass.CallStatic("parse", "file://" + destination);
    intentObject.Call("putExtra", intentClass.GetStatic("EXTRA_STREAM"), uriObject);
    intentObject.Call("putExtra", intentClass.GetStatic("EXTRA_TEXT"), shareText + gameLink);
    intentObject.Call("putExtra", intentClass.GetStatic("EXTRA_SUBJECT"), subject);
    intentObject.Call("setType", "image/jpeg");
    AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject currentActivity = unity.GetStatic("currentActivity");

    currentActivity.Call("startActivity", intentObject);

    }

    isProcessing = false;

    }

    }

    ReplyDelete
  24. Thanks for sharing this amazing article and i think you know about lucky patcher apk download and i think it works like a charm. PLease post more article like this and i will visit here again.

    ReplyDelete
  25. i want to share only on whatsapp is there any solution??

    ReplyDelete
  26. it is possible share instagram

    ReplyDelete
  27. how to fix this error please help??

    NullReferenceException: Object reference not set to an instance of an object
    ShareScreen+c__Iterator0.MoveNext () (at Assets/ShareScreen.cs:29)
    UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

    ReplyDelete
  28. Thanks for sharing this article and i think you know about lucky patcher 6.3.9 and i think it works fine.

    ReplyDelete
  29. I think this is an informative post and it is very useful and knowledgeable. I really enjoyed reading this post gmail login

    ReplyDelete
  30. I have a hard time describing my thoughts on content, but I really felt I should here. Your article is really great. I like the way you wrote this information. Whatsapp Video Status Download

    ReplyDelete
  31. how to convert image to bytes? I have placed image named "512.bytes" but nothing happening

    ReplyDelete
  32. The article is great, thanks to which I wrote how to post images to Whatsapp, Twitter, etc. on Android. Thank you very much.
    run 3

    ReplyDelete
  33. it is great information but image don't share facebook. ourbdshop

    ReplyDelete
  34. For this error:
    NullReferenceException: Object reference not set to an instance of an object
    ShareScreen+c__Iterator0.MoveNext () (at Assets/ShareScreen.cs:29)
    UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

    Use "byte[] dataToSave = screenTexture.EncodeToPNG ();" instead of "byte[] dataToSave = Resources.Load(imageName).bytes;"
    And the code is not working for android version 8.0 and above...

    ReplyDelete
  35. Regular visits listed here are the easiest method to appreciate your energy, which is why why I am going to the website everyday, searching for new, interesting info. Many, thank you! Funny whatsapp group link

    ReplyDelete
  36. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post.
    comment espionner le snapchat de quelqu un

    ReplyDelete
  37. After open the Whatsapp you can see the Whatsapp call screen. download GBWhatsApp

    ReplyDelete
  38. To run WhatsApp on your PC without utilizing Bluestacks, you have to pursue the these means -
    WhatsApp PC

    ReplyDelete
  39. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging..
    Mason Soiza

    ReplyDelete
  40. This comment has been removed by the author.

    ReplyDelete
  41. Since Photo Editing Services increases the quality of your pictures, it results in enhancement of the overall impression of your products as well as the company. go to this site

    ReplyDelete
  42. I’ve learned new things out of your blog post. One other thing I have observed is that in many instances, FSBO sellers will reject people. Remember, they might prefer not to use your companies. But if anyone maintain a reliable, professional connection, offering help and being in contact for about four to five weeks, you will usually manage to win a conversation. From there, a listing follows. Thanks a lot https://www.hackingadda.com

    ReplyDelete
  43. My answer will begin with an inquiry, Do you Skype? on the off chance that your answer is certain, you will know why. in any case, in the event that you don't, here is the reasons: IMO Download

    ReplyDelete
  44. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. manager whatsapp para empresas

    ReplyDelete
  45. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. estrategias whatsapp

    ReplyDelete
  46. I am hoping the same best effort from you in the future as well. In fact your creative writing skills has inspired me. Buy Real Facebook Reviews

    ReplyDelete
  47. Kindly fill me in as to whether you're searching for an article essayist for your site. You have some truly extraordinary posts and I feel I would be a decent resource. On the off chance that you ever need to take a percentage of the heap off, I'd totally love to compose some material for your web journal in return for a connection back to mine. It would be ideal if you send me an email if intrigued. Much obliged to you! Buy Real Twitter Retweets

    ReplyDelete
  48. Great Article Thanks for the information I also Have Some Social Media Information on my Blog at Shodkk About Telegram Channel for Movies I have List of Channel Link you should Join and to vist the channel to download the Link+500 Telegram Channel List

    ReplyDelete
  49. Data indicates that fifty-eight brands and original equipment manufacturers have released the application terminal of Android platform, and other thirty-three factories are going to release the products with Android platform.gerald winata gozali

    ReplyDelete
  50. I really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.Thanks alot!
    whatsapp chief marketing officer

    ReplyDelete
  51. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. MAKING AD BOARD

    ReplyDelete
  52. Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject!
    Lynnwood locksmith

    ReplyDelete