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

37 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
  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