Purplelilgirl Makes Games
Mini Tutorial: How to post score of your Unity iOS game to Facebook?

-without shelling out $65 ;)

Well, if you have $65 to spare, just check out Prime31’s Social Networking plugin (you can even get Twitter!).

Link: http://www.prime31.com/unity/

If you don’t, like 1-broke-girl/me, read on…

There are two parts to this, Unity side and Xcode side. We must find a way for Unity and Xcode to be friends and talk to one another, you know call each others’ functions, access each others’ variables etc.

First let’s take advantage of NSUserDefaults and PlayerPrefs to save some variables (you may encrypt the score variable if you are afraid of cheaters).

PlayerPrefs in Unity…

PlayerPrefs.SetString(“score”, score.ToString());

… can be read in Xcode using…

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *score = [defaults objectForKey:@”score”];

There, we know how to pass variables, what about functions…?

In order to do that, I read this tut, which is in Simplified Chinese!  (http://xys289187120.blog.51cto.com/3361352/705415). The gist of that tutorial is that you create this other class (let’s just call it Facebook.cs):

using UnityEngine;  
using System.Runtime.InteropServices;  

public class Facebook : MonoBehaviour {

    [DllImport(“__Internal”)]  
     private static extern void _PressButton0 ();  

     public static void ActivateButton0 ()  
     {  if (Application.platform != RuntimePlatform.OSXEditor)   
        {   _PressButton0 ();  
        }  
     }  
}

The _PressButton0() will actually call some code in Xcode (we’ll get to that).

Someone else in Unity has to call ActivateButton0, a GUI button, perhaps?

if(GUI.Button(new Rect(0, 0, 130, 235), “Facebook”))
{       Facebook.ActivateButton0();
}

So when the player clicks on the GUI button, ActivateButton0() will be called which will in turn call _PressButton0().

But where’s _PressButton0()?

We create a ViewController class in Xcode (let’s just call it MyView.m):

#import “MyView.h”
#import “AppController.h”

@implementation MyView

void _PressButton0()  
{   AppController *appController = (AppController*)[[UIApplication sharedApplication] delegate];

    [appController feedDialogButtonClicked];
}  

@end

So there’s _PressButton0()!

Now let’s do the Facebook related things. Go to Facebook’s Developer site and follow the tutorial: https://developers.facebook.com/docs/mobile/ios/build/

Instead of putting some stuff in ApplicationDidFinishLaunchingWithIOptions… I placed everything in a function I called feedDialogButtonClicked.

- (void) feedDialogButtonClicked {
   
    facebook = [[Facebook alloc] initWithAppId:@”221872691249521” andDelegate:self];
   
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@”FBAccessTokenKey”]
        && [defaults objectForKey:@”FBExpirationDateKey”]) {
        facebook.accessToken = [defaults objectForKey:@”FBAccessTokenKey”];
        facebook.expirationDate = [defaults objectForKey:@”FBExpirationDateKey”];
    }
   
    /**
    if (![facebook isSessionValid])
    {   [facebook authorize: nil];
    }
    **/
   
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSString *level = [defaults objectForKey:@”level”];
    NSString *score = [defaults objectForKey:@”score”];
   
    NSMutableDictionary *params =
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
     [NSString stringWithFormat: @”I just scored %@ in the %@ Level of Maru Penguin!”, score, level], @”name”,
     @”“, @”caption”,
     @”Get Maru Penguin for free in the iTunes Store”, @”description”,
     @”http://itunes.apple.com/tw/app/maru-penguin/id521096937?mt=8”, @”link”,
     @”http://a2.mzstatic.com/us/r1000/082/Purple/v4/3a/42/b5/3a42b5dc-5452-9dde-cdc8-24e24fb82363/486SkNsbbo2zaF3glfCuo0-temp-upload.iomrjeon.320x480-75.jpg”, @”picture”,
     nil]; 
    [facebook dialog:@”feed”
           andParams:params
         andDelegate:self];
}

I had a little problem with fbDidLogin (the one mentioned in the tutorial), good thing this other tutorial solved it for me: http://ebrentnelson.blogspot.com/2012/02/fbdidlogin-never-calledwhy.html

I ended up commenting out:

/**
    if (![facebook isSessionValid])
    {   [facebook authorize: nil];
    }
    **/

Because I seem to be able to post feeds to my Facebook wall even without it (don’t know why, anyone care to explain?).

Another helpful link: How to include a link in my feed-post using FBConnect from iPhone app? (http://stackoverflow.com/questions/5574433/how-to-include-a-link-in-my-feed-post-using-fbconnect-from-iphone-app) This answer in this post explains stuff that you can include in your Feed Dialog pretty clearly.

And um, I think that is it. That bunch of codes can post your scores from Unity iOS to Facebook.

Now my other problem is, how to add a share link to the feed my app posted? Anyone, help?

Also check out an old blog post of mine about how to post pictures from Cocos2D iPhone to Facebook: http://purplelilgirl.tumblr.com/post/9406805856/howtoaddfacebooktococos2diphone

EDIT:

Since generated feeds don’t get the share button (I Google-d for 2 days and found nothing, at the end of it, it was a Which Avengers are You? quiz that helped me solve my problem) , do you know what I eventually did? I went back to that Cocos2D blog post and did it that way (That’s what the Avengers app did, by the way, I’m Hawkeye :D). I posted a photo of the results screen, lol, which is actually what my boss suggested in the first place. And since when you post photos, you can include captions (no advertising though), so there. Problem solved -ish.

EDIT:

Okay, I am apparently not a very good Googler, since only saw this today: http://forum.unity3d.com/threads/122681-Free-facebook-Plugin-for-Unity-iOS Free, Facebook, Unity, iOS, all the keywords that I’ve been searching for, all along was in the Unity Forums!

.

.

.

By the way, we made an app (the one in the sample), it’s a game and it’s free and it stars a penguin named Maru in search of yummy fishies around the world (so far he only got to Asia)…

Link: http://itunes.apple.com/tw/app/maru-penguin/id521096937?mt=8

How to find out the language of your iPhone when using Unity?

For localizations and stuff, you know? Like say if you want your game to support different languages like English, Chinese, Japanese and stuff.

There’s Application.systemLanguage (I think it’s supported on iOS now, since I tested it on my device and it returns the correct language). It supports these languages: Afrikaans, Arabic, Basque, Belarusian, Bulgarian, Catalan, Chinese, Czech, Danish, Dutch, English, Estonian, Faroese, Finnish, French, German, Greek, Hebrew, Hugarian, Icelandic, Indonesian, Italian, Japanese, Korean, Latvian, Lithuanian, Norwegian, Polish, Portuguese, Romanian, Russian, Serbo-Croatian, Slovak, Slovenian, Spanish, Swedish, Thai, Turkish, Ukrainian, Vietnamese and Hungarian. And if your selected language is not on that list, it returns: Unknown. So if the language that you want to support is on that list, you don’t have to read the rest of this post. Application.systemLanguage is all you need.

But, but, if you are like me (Taiwanese/Chinese), you might need to support not just Chinese, but Simplified and Traditional Chinese (there is a difference), unfortunately Application.systemLanguage, doesn’t know that difference. But the iOS SDK does.

So I want to use iOS SDK’s way of identifying languages using the code:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *languages = [defaults objectForKey:@”AppleLanguages”];
    NSString *currentLanguage = [languages objectAtIndex:0];

I then save the current language to NSUserDefaults:

[[NSUserDefaults standardUserDefaults] setObject:currentLanguage forKey:@”language”];
[[NSUserDefaults standardUserDefaults] synchronize];

So I can access it in Unity, using PlayerPrefs:

PlayerPrefs.GetString(“language”)

So here’s the thing the iOS code needs to be added in AppController.mm that’s generated when you build Unity iOS.

I added that part before Unity gets called ([self startUnity:application]) inapplication didFinishLaunchingWithOptions.

But, but, every time you build, AppController.mm gets overwritten, so, so, what now?

After Unity 3.5, all you have to do is to drag and drop your AppController.mm file into Plugins/iOS folder inside Unity Assets folder and that copy will automatically overwrite whatever that is generated.

And that is it! :)

» Make A 2D Game in Unity3D Using Only Free Tools Part 1
» How to iTween GUI elements in Unity3d?

(it’s a link to Unity Answers)

» Unity Mobile Basic (iOS and Android) are free until April 8!

Check out…

Oh, and Unity has a new store site :)

MonoDevelop Unity error- wut? o.o
Yeah, I think it’s supposed to display in some other language. But somehow I find this box error kind of fun looking.


MonoDevelop Unity error- wut? o.o

Yeah, I think it’s supposed to display in some other language. But somehow I find this box error kind of fun looking.

» Optimising with Unity for iOS
» Packt Publishing is about to give away 100 Unity3D books

Marketing blurb aside, the main point of that post is:

Here’s how it works.

1) Someday soon they will announce the release of Unity iOS Game Development Beginner’s Guide from the @packtexplorer twitter account using the code #unityiosRT

2) The first 100 unique re-tweets get the book free!

3) You need to be a follower of @packtexplorer (if you’re doing gamedev you probably should be following @packtexplorer anyway!) so that we can contact you.

4) You need to have a Packtpub account with your email and address so that we can credit your book to that account.

5) A couple of days after the announcement we will list the twitter @username of the 100 winners. If you’ve won, send a DM (twitter direct mail) to claim, including the email you used to set up your Packtpub account.

6) The book will appear on your account for you to download as a pdf or epub on your tablet or ereader.

So watch @packtexplorer for the announcement with the code word #unityiosRT

Unity Books Giveaway Contests hosted by other lovely people

So am browsing the Unity3D forums and noticed that not one but two people (blogs) are hosting book giveaway contests!

 

Unity iOS EssentialsUnity 3.x Game Development Essentials

ABitGames Dev Blog are giving away 6 copies of Unity 3.x Game Development Essentials and Unity iOS Essentials.

Link: http://abitgames.com/2012/blog/great-unity-books-giveaway-contest/

Will Goldstone, the author of Unity 3.x Game Development Essentials, is also holding a giveaway for his book.

Link: http://www.willgoldstone.com/blog/2012/01/win-free-copies-of-unity-3-x-game-development-essentials-book/

So head on over to those blogs and join some contests (I did, I want to win myself a copy of Unity 3.x Game Development Essentials, since I have the first edition and find it quite helpful).

Move quickly, their contest ends of February 15 (day after Valentine’s?)

Note: I am not affiliated with any of the aforementioned blogs and authors.

Quick Review: Unity iOS Essentials

I am currently reading “Unity iOS Essentials”, which I won from ManiacDev’s book giveaway contest.

Unity iOS Essentials

And so far, I find that this book seems to be all over the place and it inspires to be a Game Design book.

Why made me think so? Well, Chapter 1 is about Planning Ahead for an Unity iOS Game, it starts out pretty clear, it aims to give the readers a little heads up before they start their game, it mentions considerations such as terrain, lighting, audio, etc. And then it got to the Let’s Get Started part, which is pretty much the author make all sorts of game design suggestions, and sometimes he would suggest something and not really explain why, such as he said that Fog is not such a great idea, and he suggests that we use particles instead, but why? Why isn’t fog a good idea? He even mentioned that it adds ambiance, so why isn’t it a good idea? Also there is a whole chunk that he talks about teleportation (wut? o.O), which provides means for players to travel across our large levels. He could have ended that bit there, but he goes on to suggest different ways of doing teleportation, warp gates, trains, what nots. And then after being distracted by all those really not important stuff, he starts talking about culling. Now, culling is important (even the author says so). But the reader could have skipped that part (okay, at least I almost skipped that part because I was skipping the trying to skip the teleportation part).

Chapter 2 is called iOS Performance Guide, but like Chapter 1, instead of getting right down to it (the performance guide), he starts the chapter with different kinds of games that the reader can make. And briefly mention skybox and how we’re supposed to use a cube with reversed normals instead of the one that Unity came with (again, no explanation whatsoever on why we shouldn’t use the Unity one). And then some bits about how we should do our terrain (not the technical part, the design part of making a terrain). Some more bits about different game genres.And then suddenly, Unified Graphic Architecture and the other stuff that actually seems like the iOS Performance Guide.

Chapter 3 is called Advanced Game Concepts, but really the things covered in the chapter is not very advanced, it’s stuff about menus, interface, screen sizes, accelerometer, shaders and organizing your assets.

Chapter 4 is called Flyby Background. Can’t say anything about it, because I skipped it.

I’m after Chapter 5 because it’s about Scalable GUIs, which I happen to be working on right now. So far, it’s understandable, pretty easy to follow. But the way the code bits are edited makes it somewhat unreadable. Oh and don’t expect the code to work as is.

That’s where I am right now, there are still four more chapters that I haven’t read yet.

So far, my comment is, it’s all over the place.

Link: http://www.packtpub.com/unity-3d-essentials-for-ios-games/book

Unity 3D Game Development by Example Beginner’s Guide: Game #2

A few months ago, I wrote a blog post on #AltDevBlogADay reviewing a Unity3D book written by Ryan Henson Creighton, Unity 3D Game Development by Example Beginner’s Guide (buy the book, it’s pretty good, so far), but I only gotten around to Chapter 4.

Unity 3D Game Development by Example Beginner's Guide

So for this blog post, I will go through some of the other chapters, particularly Chapter 5 and 6, which is about making a game called “Robot Repair”.

Chapter 5 will talk about GUI (graphical user interface, pronounced as “gooey”, like marshmallows). And we’ll be making an entire working 2D flip n’ match memory game in the GUI system.

So let’s get started!

First we open Unity and create a new project called “Robot Repair”, we don’t need to import Standard Assets, according to the boss (Mr. Author, Ryan Henson Creighton).

So we have an empty slate (este project).

A Unity scene is a big 3D world, but we would be ignoring that for now. We will be using the GUI layer, which is like “a sheet of glass” in front of our 3D world.

We will be making 2 scenes for this game. A scene is like a level or a screen in our game. So two scenes, one for the title and one for the game game.

(how organized are we)

So we are making the title screen first.

(tada!)

Of course, so far the TitleGUI script is still empty.

And we type some code (este copy paste from the book):

And we get this:

And if you clicked the button, you get a lil message:

(yeah)

The book came with some code files and assets for each chapter, packed as Unity packages, just double click on the file and it’ll import it to your project.

For the title screen, the author has prepared a cute image that we will add as a GUITexture, and so we get this:

(oh, we also changed the position of the button, so it’s front and well, not really center)

And then hook the button to some code that will bring us to the game:

Application.LoadLevel(“game”);

(yes, this short little code will bring us to the next scene, if we have our scenes added to our build settings)

Lalala… okay, time to make the actual game game.

We go to the game scene (just double click on the scene in the Project panel).

And we’ll make a GameScreen game object and a GameScript script (like what we did with the title screen).

Ooh… what codes will we fill this new script with? *copy paste some codes from the book* Okay, and read up on the explanations too.

And we get this!

(whee)

And then we are done with one chapter. Look at us, pretty good, huh.

Mini Tutorial: How to batch replace textures with different file formats in Unity?

In relation to my previous tutorial: Mini Tutorial: How to batch convert image files to PVR (for iPhone app development)?

So you have a Unity project that was previously not planned for iOS (for PC, Mac or web or whatever), and you might not be as conscious of the texture file formats (iOS is probably the only one with so many constraints).

According to Unity’s User Manual:

Use iOS native PVRT compression formats. They will not only decrease the size of your textures (resulting in faster load times and smaller memory footprint), but also can dramatically increase your rendering performance! Compressed texture requires only a fraction of memory bandwidth compared to full blown 32bit RGBA textures.

So after converting all my textures (or creating a copy of my textures in .pvr format using Automator), I’m supposed to change all the material textures in my Unity Project and that’s a lot. So I wrote this tiny Editor script to do that for me. It will even delete the old texture (.tga or .png or whatever) from the Assets folder.

So here it is:

using UnityEngine;
using System.Collections;
using UnityEditor;                      
 
public class ChangeTexturesToPVR : ScriptableWizard
{
     [MenuItem (“Project Tools/Change Textures to PVR”)]
    static void MakeFolder ()
    {   ChangeTextures();
    }
 
    static void ChangeTextures()
    {
        string filePath = AssetDatabase.GetAssetPath(Selection.activeGameObject);
        int index = filePath.LastIndexOf(“/”)+1;
        filePath = filePath.Remove(index);
        
        foreach (Transform child in Selection.activeGameObject.transform)
        {    Material[] mats = child.renderer.sharedMaterials;
           
            foreach(Material mat in mats)
            {    string texFilePath = filePath;
                texFilePath = texFilePath.Insert(texFilePath.Length, “Texture/”);
                if(mat.mainTexture != null)
                    texFilePath = texFilePath.Insert(texFilePath.Length, mat.mainTexture.name);
               
                string oldTexFilePath = texFilePath;
                oldTexFilePath = oldTexFilePath.Insert(oldTexFilePath.Length, “.tga”);
               
                texFilePath = texFilePath.Insert(texFilePath.Length, “.pvr”);
               
                mat.mainTexture = (Texture)AssetDatabase.LoadAssetAtPath(texFilePath, typeof(Texture));
                AssetDatabase.DeleteAsset(oldTexFilePath);
            }
        }
       
       
    }
}

If your old textures are in “.png”, just change “.tga” in the code above to well, “.png”.

Select the model (.fbx or .obj file) whose materials and textures that you would want to change.

And then go to the menu and click Project Tools > Change Textures to PVR (yes, I created a Menu item for it).

And then voila!

UPDATE:

I edited the code a bit:

using UnityEngine;
using System.Collections;
using UnityEditor;                     

public class ChangeMaterialTexturesToPVR : ScriptableWizard
{
     [MenuItem (“Project Tools/Change Material Textures to PVR”)]
    static void MakeFolder ()
    {   ChangeTextures();
    }

    static void ChangeTextures()
    {
        for(int i=0; i < Selection.gameObjects.Length; i++)
        {    if(Selection.gameObjects[i].transform.childCount == 0)
            {    changeTexture(Selection.gameObjects[i].transform);
            }
            else
            {    foreach (Transform child in Selection.gameObjects[i].transform)
                {    changeTexture(child);   
                }
            }
        }
    }

    static void changeTexture(Transform obj)
    {   
        if(obj.renderer)
        {    Material[] mats = obj.renderer.sharedMaterials;

            foreach(Material mat in mats)
            {   
                string texFilePath = “”;

                if(mat.mainTexture != null)
                {    texFilePath = AssetDatabase.GetAssetPath(mat.mainTexture);

                    if(!texFilePath.Contains(“.pvr”))
                    {    texFilePath = texFilePath.Remove(texFilePath.IndexOf(“.”));

                        string oldTexFilePath = texFilePath;
                        oldTexFilePath = oldTexFilePath.Insert(oldTexFilePath.Length, “.tga”);

                        texFilePath = texFilePath.Insert(texFilePath.Length, “.pvr”);

                        Texture tex = (Texture)AssetDatabase.LoadAssetAtPath(texFilePath, typeof(Texture));

                        if(tex != null)
                        {    mat.mainTexture = tex;
                            AssetDatabase.DeleteAsset(oldTexFilePath);

                            Debug.Log(texFilePath);
                        }    else
                        {    tex = (Texture)AssetDatabase.LoadAssetAtPath(oldTexFilePath, typeof(Texture));
                            mat.mainTexture = tex;

                            //Debug.Log(oldTexFilePath);
                        }
                    }
                }
            }

            obj.renderer.sharedMaterials = mats;
        }
    }
}

Now, all you have to make sure is that the .pvr and the .tga (you can change this to .png or .tif or .whatever), is in the same folder and that’s it.

That’s about it.

» Unity 3.4 Released With Tons of New Features, Tweaks and More
Review: Unity 3D Game Development by Example Beginner’s Guide

Unity 3D Game Development by Example Beginner's Guide

This is an excerpt of my previous blog post.

This book is written by Ryan Henson Creighton aka Cassie the 5 yr old game developer’s dad. This book is about 380 something pages, and it takes you through Unity from the basics (as in what Unity is, what you can and cannot do *hint* MMOs unless you are really popular and has like a hundred friends or something). And then he teaches through examples, hence the title of the book. He also gives readers programming basics. All in all, the author is actually quite a fun read, because of his wit and humor, and it is nothing like my Computer Programming 1 professor, who tends to drone.

Overall, I think this book is easy read, it’s not intimidating in such a way that it bombards you with information, code bits that you can’t even begin to grasp. I think that beginners, even those who have “never coded before” would find this book easy to digest, and might even be able to “build fun games”.

For those who are interested in the book, you can check it here. The book actual offers samples codes and projects that you can download even if you haven’t bought the book, here.

1 2   Next »