This was working. I was trying to get the login button to disappear when the user was logged on. If the user hit the login button when they were already logged in the app crashes.
What’s the deal with this.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook;
public class FB_init : MonoBehaviour
{
bool isEnabled;
bool isLogged;
string userId;
Texture pic;
void Start()
{
// Must call FB.Init Once
FB.Init(SetInitFB, SetAvailability);
FB.PublishInstall();
}
void Awake()
{
isEnabled = false;
isLogged = false;
userId = "not received";
}
private void SetInitFB()
{
// This method method will be called withing the callback received by FB.Init()
isEnabled = true;
}
private void SetAvailability(bool a_status)
{
// This method method will be called withing the callback received each time Unity gets or looses Focus (True/false)
}
void LoginCallback(FBResult result)
{
if (result.Error != null)
{
Debug.Log("Receive callback login error :: " + result.Error.ToString());
}
else
{
if (FB.IsLoggedIn)
{
// Case login was successful
isLogged = true;
userId = FB.UserId;
}
else
{
// Case login failed (because of cancelling for example)
isLogged = false;
}
}
}
void GetProfilePicAnswer(FBResult response)
{
// This method method will be called withing the callback received by FB.API()
// You can add a control here for any kind of failure to print up a default picture for example
if (response.Texture != null)
{
pic = response.Texture;
}
}
void OnGUI()
{
if (isEnabled == true)
{
if (!isLogged)
{
if (GUI.Button(new Rect(Screen.width / 2 + 300, 10, 200, 75), "Login"))
{
FB.Login("email, publish_actions", LoginCallback);
}
}
}
if (GUI.Button(new Rect(Screen.width / 2 + 300, 300, 200, 75), "GetPic"))
{
StartCoroutine(TakeScreenshot());
}
if (GUI.Button(new Rect(Screen.width / 2 + 300, 100, 200, 75), "Post"))
{
FB.Feed(
linkCaption: "",
picture: "",
linkName: "",
link: "");
}
if (GUI.Button(new Rect(Screen.width / 2 + 300, 200, 200, 75), "Invite"))
{
FB.AppRequest(
message: "",
title: "");
}
if (pic != null)
{
GUI.DrawTexture(new Rect((Screen.width - pic.width) / 2, (Screen.height - pic.height) / 2, pic.width, pic.height), pic);
}
}
void Callback(FBResult result)
{
}
private IEnumerator TakeScreenshot()
{
yield return new WaitForEndOfFrame();
var width = Screen.width;
var height = Screen.height;
var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
byte[] screenshot = tex.EncodeToPNG();
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("image", screenshot, "");
wwwForm.AddField("message", "");
FB.API("me/photos", Facebook.HttpMethod.POST, Callback, wwwForm);
}
}