I am working in a unity project I need to get email address, first name and last name of authenticated local player.
Can we get it?
thanks
Use the Social interface.
You authenticate with
Social.localUser.Authenticate(callback);
Then you can access all the user info using
Social.localUser
See the example from https://docs.unity3d.com/ScriptReference/Social-localUser.html below
using UnityEngine;
class c {
void foo() {
Social.localUser.Authenticate (success => {
if (success) {
Debug.Log ("Authentication successful");
string userInfo = "Username: " + Social.localUser.userName +
"\nUser ID: " + Social.localUser.id +
"\nIsUnderage: " + Social.localUser.underage;
Debug.Log (userInfo);
}
else
Debug.Log ("Authentication failed");
});
}
}
If the info about the player you need is not available but should be (through the native gamecenter API), then you might have to download another platform plugin for unity to use with the Social interface (as you would have to do for Android)
Related
I'm using Google Play Games service in my unity game and want to silently login my game so that the dialogue popup at the top shows only once.
Right now everytime I open the game that dialogue comes up. like this
And it takes around 5s for the dialog thing to complete that's why I want to do it silently so that user can directly enter to game if they have just signed in.
I've seen in some games that when we opens the game for the very first time only then that dialogue comes and on next further opening the dialogue doesn't comes and we directly enter to the game.
My code is
void Start()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.AddOauthScope("profile")
.RequestServerAuthCode(false)
.Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
if (!PlayGamesPlatform.Instance.localUser.authenticated)
{
Debug.Log("We're not authenticated in, let's authenticate first");
PlayGamesPlatform.Instance.Authenticate(SignInInteractivity.CanPromptOnce,
(code) =>
{
if (code == SignInStatus.Success)
{
Debug.Log("We're not signed in, let's signin first");
/// Signed in! Hooray!
PlayFabClientAPI.LoginWithGoogleAccount(new LoginWithGoogleAccountRequest()
{
ServerAuthCode = PlayGamesPlatform.Instance.GetServerAuthCode(),
CreateAccount = true,
}, OnGoogleLoginSuccess, error =>
{
Debug.Log("Error " + code);
// TODO: Move to splash scene with practice mode only
});
}
else
{
/// Error signing in. We'll want to show a sign in button
}
}); /// <--- That "true" is very important!
}
else
{
Debug.Log("We're already signed in");
}
}
so the main issue is that PlayGamesPlatform.Instance.localUser.authenticated
always returns false.
Thanks!
I'm trying to give the user the possibility to post a screenshot of his game on facebook with the dowload link of the game.
I've looked a bit and it seemed it would be possible with FB.API, but I can't manage to make it work.
Aparently you need a permission but I can't to find which permission and how to give it.
I'm using unity 2020.3.21f1
Here is what I'm doing for now
public void ShareScreenShot(Texture2D screenShot)
{
byte[] encodedScreenShot = screenShot.EncodeToPNG();
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("image", encodedScreenShot, "ScreenShot.png");
wwwForm.AddField("message", "Venez me défier : https://randomlink.blablabla");
FB.API("me/photos", HttpMethod.POST, ShareScreenShotCallback, wwwForm);
}
void ShareScreenShotCallback(IResult result)
{
if (result.Error != null)
{
Debug.Log(result.Error);
}
else
{
Debug.Log("sharing success");
}
}
If anyone of you knows how it can be done, it would be of great help, thanks
I suppose you need to login to facebook with custom permissions, because the default one only allows you to send invitations to choosen friends.
https://developers.facebook.com/docs/unity/reference/current/FB.LogInWithPublishPermissions/
I'm building a PWA using Web Bluetooth API. Connection is OK, I set an eventlistener for getting data and when my Arduino with BLE module HM10 send data, I get them.
But my PWA has more than one page. So on first one I have a "Connection" button, and after connection I "listen".
When I go to a second page, I use navigator.bluetooth.getDevices() to get previsouly connected device.
But I get an empty list.
I though my getDevices() function was bugged but I discoverd a strange thing:
my PWA run a browser tab on Chrome. I connect to the device. Then, on another tab I open this url with a Google example (https://googlechrome.github.io/samples/web-bluetooth/get-devices.html) and call Get Bluetooth Devices to get list of connected device, I see my device in this example page.
Without closing this second tab, I use my PWA: all page are able to get the device (using navigator.bluetooth.getDevices()), set the even and get data from the Arduino. Great!
If I close this tab, connection is lost...
So I think my "connection" is not perfect and when I close my PWA first page, I loose it... But as example avaible on internet are about "one page", I'm a bit lost (like the device connection in fact...).
Here is the code I use:
function reconnect_ble()
{
console.log('Search previously connected devices...');
navigator.bluetooth.getDevices()
.then(devices => {
console.log('> Got ' + devices.length + ' Bluetooth devices.');
if (devices.length == 0)
{
alert("No module");
return false;
}
var flag_module = false;
for (const device of devices)
{
var nom = device.name;
// Check if it's our modle
if (nom == pwa_hm10)
{
flag_module = connectToBluetoothDevice(device);
}
}
if (flag_module == false)
{
alert("Nothing for us");
return false;
}
else
{
return true;
}
})
.catch(error => {
console.log('Erreur:' + error);
});
}
//===================================================================================
// First Connection
function connect_ble()
{
return (deviceCache ? Promise.resolve(deviceCache) :
requestBluetoothDevice()).
then(device => connectToBluetoothDevice(device)).
catch(error => display_info(error));
}
//-------------------------------------------------------------------------------------
function connectToBluetoothDevice(device)
{
const abortController = new AbortController();
// Evenement sur ce device
device.addEventListener('advertisementreceived', (event) =>
{
console.log('connectToBluetoothDevice- Advertisements from "' + device.name + '"...');
// Stop watching advertisements to conserve battery life.
abortController.abort();
// Connexion au serveur GATT
device.gatt.connect()
.then(() =>
{
console.log('connectToBluetoothDevice - Server GATT from "' + device.name + '"...');
// Set our event
connectDeviceAndCacheCharacteristic(device).
then(characteristic => startNotifications(characteristic)).
catch(error => display_info(error));
})
.catch(error =>
{
// Erreur pas de connexion
console.log(error);
});
}, { once: true });
console.log('connectToBluetoothDevice - Watching advertisements from "' + device.name + '"...');
device.watchAdvertisements({ signal: abortController.signal })
.catch(error =>
{
console.log(error);
});
}
//----------------------------------------------------------------------------------
// Form to choose device
function requestBluetoothDevice()
{
return navigator.bluetooth.requestDevice(
{
acceptAllDevices: true,
optionalServices: [0xFFE0]
}).
then(device => {
display_info('Selected: ' + device.name);
deviceCache = device;
deviceCache.addEventListener('gattserverdisconnected',handleDisconnection);
return deviceCache;
});
}
//-----------------------------------------------------------------------------------
function connectDeviceAndCacheCharacteristic(device)
{
if (device.gatt.connected && characteristicCache)
{
return Promise.resolve(characteristicCache);
}
return device.gatt.connect().
then(server => {
return server.getPrimaryService(0xFFE0);
}).
then(service => {
return service.getCharacteristic(0xFFE1);
}).
then(characteristic => {
display_info('characteristic founded');
characteristicCache = characteristic;
return characteristicCache;
});
}
//------------------------------------------------------------------------------------
function startNotifications(characteristic)
{
return characteristic.startNotifications().
then(() => {
characteristic.addEventListener('characteristicvaluechanged',handleCharacteristicValueChanged);
});
}
//--------------------------------------------------------------------------------------
function handleCharacteristicValueChanged(event)
{
// Decoding received data
var decodage = new TextDecoder().decode(event.target.value);
traitement_data_ble(decodage);
}
Edit
If you connect to the bluetooth on Page 1, and go to Page 2 on same tab, connection is lost.
If you connect to the bluetooth on Page 1, set an event listenner to get data then open Page 2 on another tab, Page 2 will "see" the bluetooth module, but even if Page 2 set an event listener, this is even from Page 1 that will receive the data.
If you connect to the bluetooth on Page 1, don't set event listenner, open Page 2 in other tab and set event listenner on Page 2, Page 2 will receive the data.
So case 3 seems to be the only way. Maybe using iFrame for the connection page??
Accessing the same device from multiple pages is not supported and the fact that it seems to partially work is more of a bug than a feature. A device can't effectively distinguish between multiple pages on the same host trying to communicate with it so you need to have a single piece of code which manages the connection to the device.
The correct way to do this today is to create a single-page application so that the connection held by that page can remain own even if the user navigates to different "pages" of your application. If you need to create separate windows these can communicate with the device by sending commands back through the single page that owns the connection using postMessage or Broadcast Channel.
The ideal solution, which is not currently supported, is to use a Shared Worker for this. Shared Workers are a type of web worker which is owned by all the currently open pages of your app at once. It can thus hold shared state (such as the Bluetooth connection) in behalf of your application and won't exit unless every window of your app is closed.
private string text;
void Start()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestIdToken().RequestServerAuthCode(false).Build();
text = "config created";
PlayGamesPlatform.InitializeInstance(config);
text = text + "\n" + "config initialized";
PlayGamesPlatform.Activate();
text = text + "\n" + "activated";
SignInWithPlayGames();
text = text + "\n" + "attempted to sign in";
}
public void SignInWithPlayGames()
{
UnityEngine.Social.localUser.Authenticate((bool success) =>
{
if (success)
{
string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
text = text + "\n" + "Auth code is: " + authCode;
if (string.IsNullOrEmpty(authCode))
{
text = text + "\n" + "Signed into Play Games Services but failed to get the server auth code.";
return;
}
}
if (!success)
{
text = text + "\n" + "Failed to Sign into Play Games Services.";
return;
}
});
}
When I run this on Unity, I got
config created
config initialized
activate
Failed to Sign into Play Games Services.
attempted to signed in
which is fine since I am using my PC to test it. But I got an interesting result after I run my app on a real device. I got this:
config created
config initialized
activate
attempted to signed in
I think it skip if (success) from public void SignInWithPlayGames() method. My app never shows Google Play UI and I am not sure now if I am using the right code.
I've struggled quite a bit with Google Play in the last few weeks. I did not Retrieve the ID token or auth token in the builder however. It might be causing you problems.
Also, you need to cast the social user into a google user to access its properties.
I got it to work with the following code. (If you do not get it to work with this code, the problem resides in your settings in the googleplay Plugin and/or google play console.)
PlayGamesClientConfiguration config = new
PlayGamesClientConfiguration.Builder()
.Build();
// Enable debugging output (recommended)
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
Social.localUser.Authenticate((bool success) =>
{
var googleUser = ((PlayGamesLocalUser)Social.localUser);
if (googleUser.authenticated)
{
// access googleUser properties and store them or use them
}
}
hope that some body answer.. thanks in advance
I trying to integrate Facebook Sign In in Intel XDK but I only gets a blank screen and a button Cancel on top... any help here is my code
function facebook_login(){
document.addEventListener("intel.xdk.facebook.login",function(e){
if (e.success == true)
{
var facebookUserID = "me"; //me = the user currently logged into Facebook
document.addEventListener("intel.xdk.facebook.request.response",function(e) {
console.log("Facebook User Friends Data Returned");
if (e.success == true) {
var data = e.data.data;
var outHTML = "";
for (var r=0; r< data.length; r++) {
outHTML += "<img src='http://graph.facebook.com/"
+ data[r]["id"]
+ "/picture' info='"
+ data[r]["name"] + "' />";
}
alert(outHTML);
document.removeEventListener("intel.xdk.facebook.request.response");
}
},false);
}
else
{
console.log("Unsuccessful Login");
}
}, false);
intel.xdk.facebook.login("publish_stream, publish_actions, offline_access");
}
I'm not 100% sure but if you look at the end of this page : https://software.intel.com/en-us/html5/articles/integrating-facebook-functionality-into-hybrid-apps-using-the-intel-xdk
You'll see that you need to register your app through facebook and then build it.
Bye.
The intel.xdk.facebook library only works in the Legacy Builds that can be generated from the XDK IDE. It will not work in the XDK emulator, AppPreview, or Cordova Builds. Below is the forum link where IntelJohn points this out. I have confirmed this with independent testing.
https://forums.html5dev-software.intel.com/viewtopic.php?f=34&t=6444&sid=5b50fedfdfcb924a3f69579af01285c1
If your application will rely on any Cordova plugins (meaning you'll have to use the Cordova build) it would be better for you to drop use of the intel.xdk.facebook library and install the Cordova Facebook Plugin (https://github.com/Wizcorp/phonegap-facebook-plugin).