Monday, April 20, 2015

How to set up google play services with unity plugin for android



below notes are taken directly from https://github.com/playgameservices/play-games-plugin-for-unity  webpage. here I copied that article,  only making a quick access for myself. Also I wrote some extra notes. For full page please goto https://github.com/playgameservices/play-games-plugin-for-unity website.

how to google play services with unity plugin:

First of all, build your game and upload it to google play services.



1) goto https://github.com/playgameservices/play-games-plugin-for-unity and clone git repository, or download and unzip the zip file.
2) find latest unity package, it is under the current_build directory, its name is something like "current-build/GooglePlayGamesPluginForUnity-X.YY.ZZ.unitypackage"
3) open the Android SDK manager and verify that you have downloaded the Google Play Services package. The Android SDK manager is usually available in your SDK installation directory, under the "tools" subdirectory, and is called android (or android.exe on Windows). The Google Play Services package is available under the Extras folder. If it is not installed or is out of date, install or update it before proceeding.
4) set up the path to your Android SDK installation in Unity. This is located in the preferences menu, under the External Tools section.
5) configure your game's package name. To do this, click File | Build Settings, select the Android platform and click Player Settings to show Unity's Player Settings window. In that window, look for the Bundle Identifier setting under Other Settings. Enter your package name there (for example com.example.my.awesome.game).
6) click the Window |Google Play Games|Setup - Android setup menu item. This will display the Android setup screen, where you must input your Application ID (e.g. 12345678012). You will get your application id from google services page. click the Setup button.

Important: The application ID and package name settings must match exactly the values you used when setting up your project on the Developer Console.


=======================


How to manage with your code:
-------------------------------
The Google Play Games plugin implements a subset of Unity's social interface. The standard API calls can be accessed through the Social.Active object, which is a reference to an ISocialPlatform interface. The non-standard Google Play Games extensions can be accessed by casting the Social.Active object to the PlayGamesPlatform class, where the additional methods are available.



Sign in:
------------------------------------------
To sign in, call Social.localUser.Authenticate, which is part of the standard Unity social platform interface.

    using GooglePlayGames;
    using UnityEngine.SocialPlatforms;
    ...
    // authenticate user:
    Social.localUser.Authenticate((bool success) => {
        // handle success or failure
    });
Authentication will show the required consent dialogs. If the user has already signed into the game in the past, this process will be silent and the user will not have to interact with any dialogs.

Note that you cannot make any games API calls (unlock achievements, post scores, etc) until you get a successful return value from Authenticate, so it is good practice to put up a standby screen until the callback is called, to make sure the user can't start playing the game until the authentication process completes.

WARNING: dont forget to set googleplayservices ad default social platform!!!

void Awake () {
// Select the Google Play Games platform as our social platform implementation
GooglePlayGames.PlayGamesPlatform.Activate();
}
how to check if an user is logged in or not?
public bool isLoggedInGooglePlayServices() {
bool sonuc = false;
if(Social.localUser.authenticated) {
sonuc = true;
}
return sonuc;
}


Sign out
------------------------------------------
To sign the user out, use the PlayGamesPlatform.SignOut method.

    using GooglePlayGames;
    using UnityEngine.SocialPlatforms;

    // sign out
    PlayGamesPlatform.Instance.SignOut();
After signing out, no further API calls can be made until the user authenticates again.




Revealing/Unlocking an Achievement
------------------------------------------
To unlock an achievement, use the Social.ReportProgress method with a progress value of 100.0f:

    using GooglePlayGames;
    using UnityEngine.SocialPlatforms;
    ...
    // unlock achievement (achievement ID "Cfjewijawiu_QA")
    Social.ReportProgress("Cfjewijawiu_QA", 100.0f, (bool success) => {
      // handle success or failure
    });
Notice that according to the expected behavior of Social.ReportProgress, a progress of 0.0f means revealing the achievement and a progress of 100.0f means unlocking the achievement. Therefore, to reveal an achievement (that was previously hidden) without unlocking it, simply call Social.ReportProgress with a progress of 0.0f.


If your achievement is incremental, the Play Games implementation of Social.ReportProgress will try to behave as closely as possible to the expected behavior according to Unity's social API, but may not be exact. For this reason, we recommend that you do not use Social.ReportProgress for incremental achievements. Instead, use the PlayGamesPlatform.IncrementAchievement method, which is a Play Games extension.

    using GooglePlayGames;
    using UnityEngine.SocialPlatforms;
    ...
    // increment achievement (achievement ID "Cfjewijawiu_QA") by 5 steps
    PlayGamesPlatform.Instance.IncrementAchievement(
        "Cfjewijawiu_QA", 5, (bool success) => {
            // handle success or failure
    });




Showing the Achievements UI
------------------------------------------
To show the built-in UI for all achievements, call Social.ShowAchievementsUI.

    using GooglePlayGames;
    using UnityEngine.SocialPlatforms;
    ...
    // show achievements UI
    Social.ShowAchievementsUI();
This will show a standard UI appropriate for the look and feel of the platform (Android or iOS).




Posting a Score to a Leaderboard
------------------------------------------
To post a score to a leaderboard, call Social.ReportScore.

    using GooglePlayGames;
    using UnityEngine.SocialPlatforms;
    ...
    // post score 12345 to leaderboard ID "Cfji293fjsie_QA")
    Social.ReportScore(12345, "Cfji293fjsie_QA", (bool success) => {
        // handle success or failure
    });
Note that the platform and the server will automatically discard scores that are lower than the player's existing high score, so you can submit scores freely without any checks to test whether or not the score is greater than the player's existing score.




To show the built-in UI for all leaderboards, call Social.ShowLeaderboardUI.
------------------------------------------
    using GooglePlayGames;
    using UnityEngine.SocialPlatforms;
    ...
    // show leaderboard UI
    Social.ShowLeaderboardUI();
If you wish to show a particular leaderboard instead of all leaderboards, you can pass a leaderboard ID to the method. This, however, is a Play Games extension, so the Social.Active object needs to be cast to a PlayGamesPlatform object first:

    using GooglePlayGames;
    using UnityEngine.SocialPlatforms;
    ...
    // show leaderboard UI
    PlayGamesPlatform.Instance.ShowLeaderboardUI("Cfji293fjsie_QA");



There are more data about cloud saving, reading from cloud or multiplayer issues on https://github.com/playgameservices/play-games-plugin-for-unity page. Since I dont need them yet, I did not gather data for them here.


Wednesday, March 11, 2015

How to Increase Unity Game Performance

I found a nice article giving some tips to optimize your game made with Unity.

for the audio performance here is a rule of thumb:

  • Short Clips – Native
  • Longer (or looping) clips – compressed in memory
  • Music – Stream from disc
  • Files which consistently cause CPU spikes – Decompress on load
sİNCE only one hardware audio stream can be decompressed at a time. Follow the rules above to cause CPU spikes. 


also be sure to check the full article on:
http://www.paladinstudios.com/2012/07/30/4-ways-to-increase-performance-of-your-unity-game/








Tuesday, March 10, 2015

mobile device screen resolutions for unity editor aspect ratios

iphone 4 portrait: 640x960
iphone 4 landscape: 960x640
iphone 6 landscape: 1136x640



for publishing to google game play here are the resolutions ofr 7 " tablet and 10 " tablet screen shots:

To help you target some of your designs for different types of devices, here are some numbers for typical screen widths:
  • 320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
  • 480dp: a tweener tablet like the Streak (480x800 mdpi).
  • 600dp: a 7” tablet (600x1024 mdpi).
  • 720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

(from http://developer.android.com/guide/practices/screens_support.html#NewQualifiers)



well found a good site explaining all picture dimensions:
look at : http://xayin.com/thisisatest.html for more info.



more to come in time...

Monday, February 16, 2015

SOLVED: Error building Player: CommandInvokationFailure: Unable to retrieve device properties. Please make sure the Android SDK is installed and is properly configured in the Editor.

If you got an error saying "Error building Player: CommandInvokationFailure: Unable to retrieve device properties. Please make sure the Android SDK is installed and is properly configured in the Editor." well it is simple to solve that.

Just open windows Task Manager, and find "adb.exe".
 Right click on adb.exe and press "End Task" at the bottom of the window.

This will kill process adb.exe, and that is it.

Just  open unity and try to rebuild your game.

This happens especially if you are using a HTC mobile device.


If killing adb.exe process won't solve your problem, there is also a program  named as adbfix, but I did not tried it, try it at your own risk, here is the link:

http://visualgdb.com/adbfix/


anyway I have a HTC mobile device and with unity it sometimes says  "Error building Player: CommandInvokationFailure: Unable to retrieve device properties. Please make sure the Android SDK is installed and is properly configured in the Editor." When this happens I just reopen the task manager and kill adb.exe process then I will be able to build my game on my htc device.


Hope this helps someone.





Sunday, January 4, 2015

voxel art for games

voxel art is what minecrafting games look like. they are 3d but with pixels, like od style pixel arts but in 3d.

there are programs to do voxel art games like http://www.crossyroad.com/press game. They used voxelshop porgram called qubicle at the url : http://www.minddesk.com/.  You can also search for free options , a quick gogole search

1)  https://www.google.com.tr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=voxel+draw

2) https://www.google.com.tr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=best+voxel+drawing+tool

a free voxel art program : voxelshop :  http://blackflux.com/node/11

how to check google play services sha1 value - setting up google play services


find more info here: https://developers.google.com/games/services/console/enabling

here are some quck notes:
To get the release certificate fingerprint:
keytool -exportcert \
-alias <your-key-name> \
-keystore <path-to-production-keystore> \
-list -v
To get the debug certificate fingerprint:
keytool -exportcert \
-alias androiddebugkey \
-keystore <path-to-debug-keystore> \
-list -v


other links : 



https://developers.google.com/games/services/android/quickstart#step_3_modify_your_code


https://code.google.com/p/google-plus-platform/issues/detail?id=554


http://stackoverflow.com/questions/16580885/google-play-game-services-unable-to-sign-in

http://gmc.yoyogames.com/index.php?showtopic=581853&page=7

Friday, September 19, 2014

What is Vector2D, Vector2D magnitude, Vector2d.normalized? Learn all about Vectors and their normalized vectors, dot product and other necessary stuff.

Hi,

Today I will explain a little bit of Vectors and their properties. We have to learn a few things about Vectors, both in 2D and 3D because we do need them in Unity. By the way, I will give Vector2D functions and try to explain using them but these rules and functions also apply to Vector3 counterparts. Just replace Vector2D with "Vector3D" , the rest is all the same.

tip: learn this basic vector knowledge well, these will help you in the long run of Unity and game making business.

Lets summarry the main parts:
1) Vector2d logic and What Vector2.normalized and Vector2d magnitude value means?
2) Dot vector product.
3) How to and Why to compare them?

I will try to explain them step by step.


First of all, what is a normalized Vector means? 
By saying normalized vector, we are talking about a vector which has a length of 1 unit. It makes a vector bigger if it has a length smaller than 1 or makes a vector smaller if it's  original length bigger than 1.

Lets say we have a Vector2D named A, which is 2 points in x and 3 points in y, like this:
Vector2D A = new Vector2D(2,3);

if we get its normalized vector, we will use "normalized" function of Vector2D. Like this:
Vector2D B = A.normalized;

Now we get a B vector, which is just a smaller copy of the original A vector. BOTH vectors have the SAME DIRECTION! this is important to know. But normalized one is just a smaller copt of the original.

Because a normalized vector has a magnitude of 1. Always. Period.

Btw, is you dont know the term "magnitede" dont worry. Magnitude is just a fancy word for "length" in mathematics. So when you hear the word "magnitude" of a vector, just think it's LENGTH.

Lets be more clear, a normalized Vector has a length of 1, and has the same direction of the original vector.

here is a picture of a vector (shown as original vector) and it's normalized vector:



Lastly, some well-known normalized Vectors:

Vector2D.right : Vector2(1, 0) : a normalized vector to the right.
Vector2D.up : Vector2(0, 1) : a normalized vector to the up.

here is an imaginary images of  static normalized Vectors.



Now to the second step...

2) Vector DOT product: 

Dont tnik too much about this term. It just compares (usually) 2 normalized vectors. This is that dot product goodness is all about. You give 2 normalized (which means 2 vectors with a length of 1) to the dot function of Vector2D, and you get a comparizon of those 2 vectors. Since they do have the same lenght (they both have 1 unit lenght remember?) the only think that they can be compared to is their direction. When you Vector.Dot 2 vectors, you get a float number! So what does that float number symbolize, how can a comparison function gives you a float number and expects you to get that comparison from that number?

Well, The main trick here is how to read that float number.

First of all, dot function always gives a float number between -1 and +1. What ever you do, whichever 2 vectors you give, you will always get a  number between -1 and 1. So here comes the magic:

a) if 2 vectors  both do have exactly the same direction, then you get number +1;
b) if 2 vectors  have completely opposite directions, , then you get number -1;
c) if 2 vectors are perpendicular, then you get number 0.
d) you get different number  between +1 and -1 for other cases which gives us a clue of their position to each other.

are you getting the point?

You can compare two vectors directions by looking at Vector2D.Dot function, which the term comes "getting a dot product of two vectors".

An example image of Dot Product Results and different two vectors:




So you learned what s a magnitude, how to get a vectors normalized value, and how to compare two normalized vectors using Vector's Dot method (getting dot product and examining the float number) now you can do some neat stuff with this knowledge, like handlind and managing  SLIDE controllers.

On my next article, I will explain how can you capture slide gestures, tap and click on mobile screen and how to optimize slide and how to get which way user slides from and slides through.. Wont last long, so hope to see you soon.






Tuesday, April 22, 2014

Android Signing - Just before you upload to Google Store you need a keytool - sign your apk file

For development you dont need but for for publishing (i.e. Android Market) you have to sign in your  apk file.

1) Locate the Publishing Settings under PlayerSettings
2) Create a new keystore by selecting a keystore name and password (confirm the password)
3) Select "Create a new key" under Key Alias
4) A new window opens; enter the necessary information.
5) Select the newly created key.
6) Build ( & Run); your app is now signed.

Dont forget your password. That is important. If you ever forget your password you cant upload your apk file later! Always remember the passwords; they are not stored with the project (for security reasons).


Big List of Indie Game Earnings - Success stories.

Found a good webpage, which has lots of indie gamer earnings. A real good list of success stories. Be sure to read on http://www.pixelprospector.com/the-big-list-of-game-revenue-sales.


Here are the links, (I wanted to archieve this if orijinal post will somehow dissapear in the future)

---


Wednesday, April 9, 2014

Unity3d - MiniJSON - Facebook SDK for Unity

MiniJSON knowledge

1) Anything that is wrapped in curly brackets {}  converts to "Dictionary<string, object>"
2) all the keys are sthe strings on the left side of the colon (:)
3) values are on the right side of the colon (:)
4) anything wrapped in square brackets [] convert to a List<object>
5) all values converts to System.String which then be converted to whatever type you want with the system string convert functions.

Some examples to serialize / deserialize facebook sdk output in Unity3D:


void OnLoggedIn()                                                                        
{                                                                                        
//Debug.Log("Logged in. ID: " + FB.UserId);
// Reqest player info and profile picture                                                                        
FB.API("/me?fields=id,first_name,last_name,picture,friends.limit(10).fields(first_name,id,last_name,picture)", Facebook.HttpMethod.GET, APICallback);
//LoadPicture(GetPictureURL("me", 128, 128),MyPictureCallback);
}

void APICallback(FBResult result)                                                                                            
{                                                                                                                            
Debug.Log("APICallback");                                                                                              
if (result.Error != null)                                                                                                
{                                                                                                                        
Debug.LogError(result.Error);                                                                                          
return;                                                                                                              
}              

myFacebookProfile = DeserializeJSONProfile(result.Text);
// Debug.Log("+++++++++++ facebook profile :" +
//          "firname: " + myFacebookProfile.first_name +
//          ", lastname:" + myFacebookProfile.last_name +
//          ",id: " + myFacebookProfile.id +
//          "picture: " + myFacebookProfile.profile_image_url+
//          ",is_silhoutte" + myFacebookProfile.Profile_image_is_silhoutte);


myFacebookFriends =  DeserializeJSONFriends(result.Text);
int i = 0;
foreach (FacebookProfile fd in myFacebookFriends) {
i++;
Debug.Log("+++++++++++" + i +") nolufriend:" +
         "firname: " + fd.first_name +
         ", lastname:" + fd.last_name +
         ",id: " + fd.id +
         "picture: " + fd.profile_image_url+
         ",is_silhoutte" + fd.Profile_image_is_silhoutte);
}
}


public FacebookProfile DeserializeJSONProfile(string response)
{
FacebookProfile profile = new FacebookProfile();
Dictionary<string, object> responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object nameH;
Dictionary<string,object> tempDictionary;

if (responseObject.TryGetValue("first_name", out nameH))
{
profile.first_name = (string)nameH;
}
if (responseObject.TryGetValue("last_name", out nameH))
{
profile.last_name = (string)nameH;
}
if (responseObject.TryGetValue ("id", out nameH)) {
profile.id = (string)nameH;
}

if (responseObject.TryGetValue ("picture", out nameH)) {
tempDictionary = (Dictionary<string,object>) nameH;
if (tempDictionary.TryGetValue ("data", out nameH)) {
tempDictionary = (Dictionary<string,object>) nameH;
profile.profile_image_url = (string) tempDictionary["url"];
profile.Profile_image_is_silhoutte = (bool) tempDictionary["is_silhouette"];
//resim bilgisi gönderilmiş ise, resmi download edelim arka planda:
if(profile.Profile_image_is_silhoutte == false) {
StartCoroutine(LoadProfilePictureEnumerator(profile));
}
}

//Dictionary<string,object> friendPictureData = (Dictionary<string,object>)((Dictionary<string,object>)responseObject["picture"])["data"];
//profile.profile_image_url = (string) friendPictureData["url"];
//profile.Profile_image_is_silhoutte = (bool) friendPictureData["is_silhouette"];
}

return profile;
}

public List<FacebookProfile> DeserializeJSONFriends(string response)
{
List<FacebookProfile> facebookFriends = new List<FacebookProfile>();
var responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object friendsH;
Dictionary<string,object> tempDictionary;

bool runned_once = false;
do {
if (!responseObject.TryGetValue("friends", out friendsH))
{
break;
}

List<object> friendsDataContainer = (List<object>)(((Dictionary<string, object>)friendsH)["data"]);
foreach (Dictionary<string,object> friendData in friendsDataContainer) {
FacebookProfile friend = new FacebookProfile();

if (friendData.TryGetValue("first_name", out friendsH))
{
friend.first_name = (string)friendsH;
}
if (friendData.TryGetValue("last_name", out friendsH))
{
friend.last_name = (string)friendsH;
}
if (friendData.TryGetValue ("id", out friendsH)) {
friend.id = (string)friendsH;
}


//resimleri bulmak için bir tur daha aşagı inecegiz

if (friendData.TryGetValue ("picture", out friendsH)) {
tempDictionary = (Dictionary<string,object>) friendsH;
if (tempDictionary.TryGetValue ("data", out friendsH)) {
tempDictionary = (Dictionary<string,object>) friendsH;
friend.profile_image_url = (string) tempDictionary["url"];
friend.Profile_image_is_silhoutte = (bool) tempDictionary["is_silhouette"];
//resim bilgisi gönderilmiş ise, resmi download edelim arka planda:
if(friend.Profile_image_is_silhoutte == false) {
StartCoroutine(LoadProfilePictureEnumerator(friend));
}
}

//Dictionary<string,object> friendPictureData = (Dictionary<string,object>)((Dictionary<string,object>)responseObject["picture"])["data"];
//profile.profile_image_url = (string) friendPictureData["url"];
//profile.Profile_image_is_silhoutte = (bool) friendPictureData["is_silhouette"];
}


//
// //var friendPictureDataContainer = friendData ["picture"] as Dictionary<string,object>;
// //var friendPictureData = friendPictureDataContainer["data"] as Dictionary<string,object>;
// Dictionary<string,object> friendPictureData = (Dictionary<string,object>)((Dictionary<string,object>)friendData["picture"])["data"];
//
// friend.profile_image_url = (string) friendPictureData["url"];
// friend.Profile_image_is_silhoutte = (bool) friendPictureData["is_silhouette"];
//
// //profile resmini arka planda download et ve profile classına yükle
// StartCoroutine(LoadProfilePictureEnumerator(friend));

//friend bilgilerini listeye ekle
facebookFriends.Add(friend);
}
runned_once = true;
} while (!runned_once);
return facebookFriends;
}


How to invite friends using Facebook SDK for Unity3D

Yıu can call this code for inviting your facebook friends using Unity3D facebook SDK.


if(FB.IsLoggedIn)
{
    FB.AppRequest(
        message: "Come and Play This Game!",
        title: "My Game Invitation For Facebook Friend",
        callback: InviteCallback
    );
}

// ...

void InviteCallback(FBResult response)
{
Debug.Log("facebook invitation from Unity3D sent");
}



if(FB.IsLoggedIn)
{
    FB.AppRequest(
        message: "Come and Play This Game!",
        title: "My Game Invitation For Facebook Friend",
        callback: InviteCallback
    );
}

// ...

void InviteCallback(FBResult response)
{
Debug.Log("facebook invitation from Unity3D sent");
}



If your app is in sandbox mode, people won't get notified when the request is sent. So change your facebook application settings to "public"  in https://developers.facebook.com/apps page, goto "Status & Review" tab on le menu on the left. On the right you will see "Do you want to make this app and all its live features available to the general public?" question. Set its value to "YES" . If you cant modify YES/NO section then you have to give your application a contact email  on "Settings" tab on left menu.



Look for the request in https://www.facebook.com/appcenter/requests as the recipient and see if the request shows up there.



How to check facebok invitations: 

If you want you can also check invitation from FBResult response object, maybe even call how many people does this invitation is sent. An example code:

private void InviteCallback(FBResult result)
    {
        if (result != null)
        {
            var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
            IEnumerable<object> objectArray = (IEnumerable<object>)responseObject["to"];

            if (objectArray.Count() >= 3)
            {
                // 3 facebook invitations send. Give user a free item or bonus etc.
            }
        }
    }


Btw, facebook also gives us nice shiny login buttons, which can be downloaded from this address: https://developers.facebook.com/docs/facebook-login/checklist .






Tuesday, April 8, 2014

How to download content or picture image in the background using WWW class?

 Unity3D has a utility module for retrieving the contents of URLs named as WWW class. WWW class can also download a picture image,  so that you can assign that picture on the internet as a Texture in your Unity3D project.



Remember, WWW class is a Coroutine and runs background.

I can recommend two different ways of implementing background downloading in Unity3D.

First way; You can just yield it until it is completed. For example:

void IEnumerator Start() {
    WWW www = new WWW( url );
    yield return www;
   Texture2D myPicture = www.texture;  //this is how you download and image from web in untiy3d.
}


Second Way;  you can inspect the isDone property of WWW class to see if the download has completed or not. Here is an example of using the isDone and progress properties:

float progress = 0.0f;
void IEnumerator Start() {
    WWW myW = new WWW( url );
    while( !myW.isDone )
    {
        progress = myW.progress;
        yield return null;
    }
    progress = 1.0f;
}

Tip: You can create a progress bar with that progress property in OnGUI function.



Thursday, April 3, 2014

Unity3D and facebook SDK login problem for android devices

So you created you Unity3D game, integrated with Facebook's shining plugin. But still you are not able to login right? Infact nothing happens when you click that login button.

here is the problem: key_store hash!

I know you installed openssl and put your key on your facebook page.

well the thing is your key_hash is not valid.

When you debug your application with adb logcat, you can see a row like this:

"W/fb4a(:<default>):BlueServiceQueue(19773): com.facebook.http.protocol.ApiException: Key hash ******* does not match any stored key hashes."

**** = a key hash which I masked for privacy reasons.

well use that key_hash on your facebook app page.

go https://developers.facebook.com/apps  and select your aplication, choose "Settings" from the menu on the left and write that key hash which you see on the adb logcat log on facebooks key hashes part.  Save and update facebook.

that is it.

If you dont know how to use adb log cat, read my article on this url:

---

Here is a quick how to use adb :

1) goto your sdk installation directory, (adt\sdk\platform-tools) and run this command:
adb logcat  > mylog.txt

this command will dump all logs to mylog.txt file. open that file and search for key hash keyword on the log.  To Search adn solve your login problem ,  do these:

i) open mylog.txt in your favourite text editor.
ii) search this word: ApiException
you will find some rows like this: 

W/fb4a(:<default>):BlueServiceQueue(26232): com.facebook.http.protocol.ApiException: [code] 404 [message]: Key hash yd13SdjudjDdwdwedWsdddcwVJW  does not match any stored key hashes. [extra]: null
( there you will find your real key hash: yd13SdjudjDdwdwedWsdddcwVJW) 

iii) put  an extra = sign at the end and key hash become like this: yd13SdjudjDdwdwedWsdddcwVJW=

iv) copy paste this keyhash into your facebook developer page. all your facebook sdk login problems will be gone. 
 ----

These steps also valid for macbook - macos unity - fcebook login sdk problems. 


There you will find your real key hash. Use this key hash on facebook key hashes form. The one unity creates is false.


------

btw Isearched a lot on internet and find these solutions below. But I did not try any of them. so you can also try these ones:

1) Some people say openssl which you install really matters and recommends to install a spesific version. Maybe with that openssl unity panel will give you the real key hash, I did not try try that.

2) Also create two key hashes one for debug one for release with these commands:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

keytool -exportcert -alias yourappreleasekeyalias -keystore ~/.your/path/release.keystore | openssl sha1 -binary | openssl base64

some urls you may invetigate further:
http://stackoverflow.com/questions/13894006/android-facebook-sdk-3-0-gives-remote-app-id-does-not-match-stored-id-while-lo/16059786#16059786

http://answers.unity3d.com/questions/576088/facebook-sdk-simple-login.html

http://stackoverflow.com/questions/13894006/android-facebook-sdk-3-0-gives-remote-app-id-does-not-match-stored-id-while-lo

http://stackoverflow.com/questions/19051361/facebook-unity-sdk-on-android-login-fails-when-fb-app-installed/19091114#19091114

http://stackoverflow.com/tags/facebook-unity-sdk/hot

http://answers.unity3d.com/questions/609810/using-facebook-api-with-android-says-login-is-canc.html


Wednesday, April 2, 2014

how to debug unity3d with adb logcat

There is something called the logcat, which is a combined message pipe from all applications. To read it you first need to locate the adb tool that comes with the Android SDK. Depending on which version you have of the SDK the adb is located either under<sdk>/tools or<sdk>/platform-tools.

Simply start it like this:

$ adb logcat

and it will start printing out everything that is going on on the device. To limit it to only show the output from inside Unity, you can try this:

$ adb logcat -s Unity

or, to get a little bit more info about what's going on:

$ adb logcat -s Unity ActivityManager PackageManager dalvikvm DEBUG

If you wish to report a bug or otherwise 'quote' the logcat, you can dump the complete logcat to a file like this:

$ adb logcat -d > logcat.txt

unity3d and facebook sdk problem - Error building Player: Win32Exception: ApplicationName='C:\Program Files (x86)\Java\jre7\bin\javac.exe',

If you are going to use facebook SDK for unity3d, then you will get these problems.

If you come across with this error: 
Error building Player: Win32Exception: ApplicationName='C:\Program Files (x86)\Java\jre7\bin\javac.exe',

then you only have Java JRE which does not come with javac.exe. You must install JAVA JDK from java website . Also be sure to read about  PATH Environment Variable (Optional) on java documentation page.  

You need JAVA JDK ! Not JRE !



here is the way to set environment table for java path: 
C:\> "C:\Program Files\Java\jdk1.7.0\bin\javac" MyClass.java
It is useful to set the PATH variable permanently so it will persist after rebooting.
To set the PATH variable permanently, add the full path of the jdk1.7.0\bin directory to the PATH variable. Typically, this full path looks something like C:\Program Files\Java\jdk1.7.0\bin. Set the PATH variable as follows on Microsoft Windows:
  1. Click Start, then Control Panel, then System.
  2. Click Advanced, then Environment Variables.
  3. Add the location of the bin folder of the JDK installation for the PATH variable in System Variables. The following is a typical value for the PATH variable:
    C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.7.0\bin
Note:
  • The PATH environment variable is a series of directories separated by semicolons (;) and is not case-sensitive. Microsoft Windows looks for programs in the PATH directories in order, from left to right.
  • You should only have one bin directory for a JDK in the path at a time. Those following the first instance are ignored.
  • If you are not sure where to add the path, add it to the right of the value of the PATH variable.
  • The new path takes effect in each new command window you open after setting the PATH variable.


also you may have to set JAVA_HOME to the directory on your machine that does have JDK (and javac.exe) installed.


here is a step by step how to change JAVA_HOME directory:

Set the JAVA_HOME Variable
Once you have the JDK installation path:
  1. Right-click the My Computer icon on
  2. your desktop and select Properties.
  3. Click the Advanced tab. Click the
  4. Environment Variables button. Under System Variables, click New.
  5. Enter the variable name as JAVA_HOME.
  6. Enter the variable value as the installation path for the Java Development Kit.
  7. Click OK.
  8. Click Apply Changes.
You might need to restart windows.
NOTE: You have to put the path to the jdk without /bin in the end.
For example:  C:\Java\jdk1.6.0_44 , NOT C:\Java\jdk1.6.0_44\bin.

You have to restart Unity3D so that unity can read the new java home path. After this you can build your unity3d game with facebook sdk without any problems.



Btw, if you need openssl for windows to create keystore for facebook sdk for unity3d, you must first download openssl and extrac its bin folder content to C:\Program Files\Java\jdk1.8.0\bin (or whereever you java install dir is) then add C:\Program Files\Java\jdk1.8.0\bin to enviroment path.

and to create keystore: 

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | penssl.exe sha1 -binary | openssl.exe base64



and the SECOND common problem is this error: 
... your android debug keystore file is missing ...

This second problem is  EASY  to fix. 
This happens when your your Unity project is on another drive than C: drive. Anyway this is not a problem. You need to fix a c# script in facebook directory in your unity project panel. Locate Facebook>Android>FacebookAndroidUtil cd file.  Open file. Find this row: 
System.Environment.GetEnvironmentVariable("HOMEPATH") + @"\.android\debug.keystore" : 
and change it with this one: 
System.Environment.GetEnvironmentVariable("HOMEDRIVE") + System.Environment.GetEnvironmentVariable("HOMEPATH") + @"\.android\debug.keystore" :

save the file. and restart unity3d. you will see that your problems will go away :) 

Monday, March 31, 2014

unity3d - hit all objects on the screen or hit only one object on the screen click

Here is an example code:


//hit only 1 object
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitScreenObject;
if(Physics.Raycast(ray,out hitScreenObject))
{
if(Input.GetMouseButtonDown(0))
{
//isHit = false;
Destroy(hitScreenObject.collider.gameObject);
}
}

//hit all objects at the same time
RaycastHit2D[] hits;
//hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
//Ray2D ray = Camera.main.ScreenPointToRay(Input.mousePosition, Vector2.zero);
                //Physics2D.raycastsHitTriggers = true;
               
                hits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
               
           


Wednesday, March 26, 2014

Unity3d Preloading Scenes with allowSceneActivation = false working (Loading scene in background)

Loading Scene in Background without switching the level immediately.


Read below to find a working (and tested)  way of loading scene in background in Unity3d. Also it wont  switch next level immediately.

If you are trying to preload a new scene, you have to use Application.LoadLevelAsync("sceneName"); method. I have managed to use this function with allowSceneActivation=false. When you set allowSceneActivation to false, you will probably sett that Unity Editor hangs. This is why you must use a different approach to achieve preloading.

IF allowSceneActivation locks up  Unity Editor  try this script:

IEnumerator LevelLoaderProcess() {
AsyncOperation status = Application.LoadLevelAsync("gameScreen");
status.allowSceneActivation = false;

// Wait until done and collect progress as we go.

//while( !status.isDone )
//{
loadProgress = status.progress;
if( loadProgress >= 0.9f )
{
Debug.Log("almost done");
// Almost done.
//break;
}
yield return null;
//}

while (!doLoadNextFrame) {
Debug.Log("still waiting");
                       //You can do whatever you want here...  
yield return new WaitForSeconds(1.0f);
}
// Allow new scene to start.
status.allowSceneActivation = true;
//yield return status;
}

You see that 0.9f if condition? Well that is the trick. When you set status.allowSceneActivation to false, unity3d stops loading target scene as soon as it loads  %90 of scenes content. And starts to wait for that 10 percent to load the next scene.  To load that 10% data, Unity3d will be waiting for status.allowSceneActivation = true; command.

Script I share above handles this issue.


Another thing to notice. DO NOT put your StartCoroutine command in AWAKE function. This also makes  unity crash, your editor crashes which makes it unresponsive. This is a Untiy3d bug I believe.  You can put a gui button in your  OnGUI  method to start your coroutines. Like this:

void OnGUI()  {
if (GUI.Button (new Rect (10, 10, 50, 50), "sirinlike")) {
StartCoroutine (LevelLoaderProcess());
}
}