Sunteți pe pagina 1din 10

Loading Level

The following snippets of code will manage levels.

This function will take a string value which is the level name.

publicvoidLoadLevel(string name){

Debug.Log ("New Level load: " + name);


SceneManager.LoadScene(name);
}

This function will load the next level automatically.

publicvoidLoadNextLevel() {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}

This method inside the start function will help in delaying level load by using Invoke().

void Start() {
if(autoLoadNextLevelAfter<= 0) {
Debug.Log("Level auto load disabled, use a positive number in seconds");
} else {
Invoke("LoadNextLevel", autoLoadNextLevelAfter);
}
}

MusicManager

The following function will load music according to level index. There will be an
array of music and each index in the array will relate to the level index or number.

voidOnLevelWasLoaded(int level) {
AudioClipthislevelmusic = levelMusicChangeArray[level];

//Debug.Log("Playing clip " + thislevelmusic);

if (thislevelmusic) {//if there is some music attached


audioSource.clip = thislevelmusic;
audioSource.loop = true;
audioSource.Play();
}
}

voidOnLevelWasLoaded(int level) is called when a new level is called.


Options Controller

Saving in playerprefs buy using Getter and setter method. The following is an example of
setting up master volume.

staticstring MASTER_VOLUME_KEY = "master_volume";

publicstaticvoidSetMAsterVolume(float volume) {
if(volume >= 0f && volume <= 1f){
PlayerPrefs.SetFloat(MASTER_VOLUME_KEY, volume);
} else {
Debug.LogError("Master volume out of range");
}
}

publicstaticfloatGetMasterVolume() {
returnPlayerPrefs.GetFloat(MASTER_VOLUME_KEY);
}

Another method that can be used for reference. This is used for unlocking levels.

staticstring LEVEL_KEY = "level_unlocked_";

publicstaticvoidUnLockLevel(int level) {
if(level <= SceneManager.sceneCountInBuildSettings - 1) {
PlayerPrefs.SetInt(LEVEL_KEY + level.ToString(), 1); //use 1 for true
} else {
Debug.LogError("Trying to unlock level not in build order");
}
}

publicstaticboolIsLevelUnlocked(int level) {
intlevelValue = PlayerPrefs.GetInt(LEVEL_KEY + level.ToString());
boolisLevelUnlocked = (levelValue == 1);

if (level <= SceneManager.sceneCountInBuildSettings - 1) {


returnisLevelUnlocked;
} else {
Debug.LogError("Trying to query level not in build order");
returnfalse;
}
}
Selection Process

publicGameObjectdefenderPrefab;
publicstaticGameObjectselectedDefender;
privateButton[] buttonArray;

void Start () {
buttonArray = GameObject.FindObjectsOfType<Button>();
}

voidOnMouseDown() {

print(name + " pressed");

foreach(ButtonthisButtoninbuttonArray) {
thisButton.GetComponent<SpriteRenderer>().color = Color.black;
}

GetComponent<SpriteRenderer>().color = Color.white;
selectedDefender = defenderPrefab;
}

Spawning on particular points in axes

publicCameramainCam;

voidOnMouseDown() {
Vector2worldpos = CalculateWorldPos();
Vector2roundedworldpos = RoundedWorldPosToInt(worldpos);
GameObjectselDef = Button.selectedButton;

//This instantiates the defender that is selected in button script


Instantiate(selDef, roundedworldpos, Quaternion.identity);
}

//This calculates the world position of mouse click


privateVector2CalculateWorldPos() {
floatmouseX = Input.mousePosition.x;
floatmouseY = Input.mousePosition.y;
floatcamDis = 10f;

Vector2worldpos = mainCam.ScreenToWorldPoint(newVector3(mouseX, mouseY, camDis));


returnworldpos;
}

//This rounds the world position to the nearest int.


privateVector2RoundedWorldPosToInt(Vector2worldpos) {
introundedWorldX = Mathf.RoundToInt(worldpos.x);
introundedWorldY = Mathf.RoundToInt(worldpos.y);

Vector2roundedworldpos = newVector2(roundedWorldX, roundedWorldY);


returnroundedworldpos;
}
Background Scaler

void Start () {
SpriteRenderer SR = GetComponent<SpriteRenderer>();
Vector3 tempScale = transform.localScale;

floatspriteWidth = SR.bounds.size.x;

floatworldHeight = Camera.main.orthographicSize * 2f;


floatworldwidth = worldHeight / Screen.height * Screen.width;

tempScale.x = worldwidth / spriteWidth;


transform.localScale = tempScale;
}

Shuffle Gameobject

void Shuffle(GameObject[] array) {


for(int i = 0; i <array.Length; i++) {
GameObject temp = array[i];
int random = Random.Range(i, array.Length);
array[i] = array[random];
array[random] = temp;
}
}

Getting Maximum and Minimum Screen Range

voidSetMinAndMaxX() {
Vector3 bounds = Camera.main.ScreenToWorldPoint
(newVector3(Screen.width, Screen.height, 0));

minX = -bounds.x + 0.5f;


maxX = bounds.x - 0.5f;
}

Controlled Randomization

voidCreateClouds() {
floatpositionY = 0;

for(int i = 0; i <clouds.Length; i++) {

Vector3 temp = clouds[i].transform.position;

temp.y = positionY;

if(controllX == 0) {

temp.x = Random.Range(0, maxX);


controllX = 1;

} elseif(controllX == 1) {

temp.x = Random.Range(0, minX);


controllX = 2;

} elseif(controllX == 2) {

temp.x = Random.Range(1.0f, maxX);


controllX = 3;
} elseif(controllX == 3) {

temp.x = Random.Range(-1.0f, minX);


controllX = 0;
}

lastCloudPositionY = positionY;

clouds[i].transform.position = temp;
positionY -= distanceBetweenClouds;

Make Singleton

voidMakeSingleton() {
if (instance != null) {
Destroy(gameObject);
} else {
instance = this;
DontDestroyOnLoad(gameObject);
}
}

Stans Assets Ad setup method

void Start() {

//Required
InitializeActions();
UM_AdManager.Init();

voidInitializeActions(){
UM_AdManager.ResetActions();
UM_AdManager.OnInterstitialLoaded += HandleOnInterstitialLoaded;
UM_AdManager.OnInterstitialLoadFail += HandleOnInterstitialLoadFail;
UM_AdManager.OnInterstitialClosed += HandleOnInterstitialClosed;
}

voidHandleOnInterstitialClosed () {
Debug.Log ("Interstitial Ad was closed");
UM_AdManager.OnInterstitialClosed -= HandleOnInterstitialClosed;
}

voidHandleOnInterstitialLoadFail () {
Debug.Log ("Interstitial is failed to load");

UM_AdManager.OnInterstitialLoaded -= HandleOnInterstitialLoaded;
UM_AdManager.OnInterstitialLoadFail -= HandleOnInterstitialLoadFail;
UM_AdManager.OnInterstitialClosed -= HandleOnInterstitialClosed;
}

voidHandleOnInterstitialLoaded () {
Debug.Log ("Interstitial ad content ready");

UM_AdManager.OnInterstitialLoaded -= HandleOnInterstitialLoaded;
UM_AdManager.OnInterstitialLoadFail -= HandleOnInterstitialLoadFail;
}

//When loading interstitial ad

InitializeActions();
UM_AdManager.LoadInterstitialAd();
isLoadads = true; //This bool value will keep track if loaded interstitial or not

//When starting interstitial ad

InitializeActions();
UM_AdManager.StartInterstitialAd();

//When showing interstitial ad

UM_AdManager.ShowInterstitialAd();
isLoadads = true;

Stans Assets Billing Method

The following should be included in the awake function

UM_InAppPurchaseManager.Client.OnPurchaseFinished += OnPurchaseFlowFinishedAction;
UM_InAppPurchaseManager.Client.OnServiceConnected += OnConnectFinished;

Initializing billing is done like this:

UM_InAppPurchaseManager.Client.OnServiceConnected += OnBillingConnectFinishedAction;
UM_InAppPurchaseManager.Client.Connect();

Checking connection state:

UM_InAppPurchaseManager.Client.IsConnected

The code snippet bellow show's how to retrieve general available products info:

foreach(UM_InAppProduct product inUM_InAppPurchaseManager.InAppProducts) {

Debug.Log("Id: " + product.id);


Debug.Log("IsConsumable: " + product.IsConsumable);

Debug.Log("Title: " + product.Title);


Debug.Log("Description: " + product.Description);
Debug.Log("Price: " + product.Price);

Debug.Log("IOSId: " + product.IOSId);


Debug.Log("AndroidId: " + product.AndroidId);
Debug.Log("WP8Id: " + product.WP8Id);

To make purchase:

UM_InAppPurchaseManager.instance.Purchase(YOUR_PRODUCT_ID);

To check is a product is purchased:

UM_InAppPurchaseManager.Client.IsProductPurchased(YOUR_PRODUCT_ID);
Restore purchases:

UM_InAppPurchaseManager.instance.RestorePurchases();

Some more codes that are taken from the billing example script

privatevoidOnConnectFinished(UM_BillingConnectionResult result) {

if(result.isSuccess) {
UM_ExampleStatusBar.text = "Billing init Success";
} else {
UM_ExampleStatusBar.text = "Billing init Failed";
}
}

privatevoidOnPurchaseFlowFinishedAction (UM_PurchaseResult result) {


UM_InAppPurchaseManager.Client.OnPurchaseFinished -=
OnPurchaseFlowFinishedAction;
if(result.isSuccess) {
UM_ExampleStatusBar.text = "Product " + result.product.id + "
purchase Success";
} else {
UM_ExampleStatusBar.text = "Product " + result.product.id + "
purchase Failed";
}
}

privatevoidOnBillingConnectFinishedAction (UM_BillingConnectionResult result) {


UM_InAppPurchaseManager.Client.OnServiceConnected -=
OnBillingConnectFinishedAction;
if(result.isSuccess) {
Debug.Log("Connected");
} else {
Debug.Log("Failed to connect");
}
}

Validation can be done using IOSStoreKitResponse for iOS and GooglePurchaseTemplate


for android

UM_InAppPurchaseManager.instance.DeleteNonConsumablePurchaseRecord(YOUR_PRODUCT_ID);

Game Services

The following code snippet was in the example scene provided.

This part should go to the Awake function.

UM_GameServiceManager.OnPlayerConnected += OnPlayerConnected;
UM_GameServiceManager.OnPlayerDisconnected += OnPlayerDisconnected;

if(UM_GameServiceManager.Instance.ConnectionSate == UM_ConnectionState.CONNECTED)
{
OnPlayerConnected();
}
Connecting to games service

UM_GameServiceManager.instance.Connect();

Disconnecting from game service

UM_GameServiceManager.instance.Disconnect();

Showing player information

if(UM_GameServiceManager.Instance.Player != null) {
GUI.Label(newRect(320, 10, Screen.width, 40), "ID: " +
UM_GameServiceManager.Instance.Player.PlayerId);
GUI.Label(newRect(320, 25, Screen.width, 40), "Name: " +
UM_GameServiceManager.Instance.Player.Name);

if(UM_GameServiceManager.Instance.Player.SmallPhoto != null) {
GUI.DrawTexture(newRect(225, 10, 75, 75),
UM_GameServiceManager.Instance.Player.SmallPhoto);
} else {
if (!_startedToLoadAvatar) {
_startedToLoadAvatar = true;
UM_GameServiceManager.Instance.Player.LoadSmallPhoto();
}
}
}

Showing Leaderboard

UM_GameServiceManager.Instance.ShowLeaderBoardsUI();

Showing particular leaderboard

UM_GameServiceManager.Instance.ShowLeaderBoardUI(leaderBoardId);

Submitting Score

UM_GameServiceManager.ActionScoreSubmitted += HandleActionScoreSubmitted;
UM_GameServiceManager.Instance.SubmitScore(leaderBoardId, hiScore);

Getting Score from a particular leaderboard

long s =
UM_GameServiceManager.Instance.GetCurrentPlayerScore(leaderBoardId).LongScore;
UM_ExampleStatusBar.text = "GetCurrentPlayerScorefrom " + leaderBoardId + " is: " + s;

Show Achievements

UM_GameServiceManager.Instance.ShowAchievementsUI();

Reset Achievements

UM_GameServiceManager.Instance.ResetAchievements();

Report Achievements

UM_GameServiceManager.Instance.UnlockAchievement(TEST_ACHIEVEMENT_1_ID);
Increment Achievements

UM_GameServiceManager.Instance.IncrementAchievement(TEST_ACHIEVEMENT_2_ID, 20f);

Handling submitted score

voidHandleActionScoreSubmitted (UM_LeaderboardResult res) {


if(res.IsSucceeded) {
UM_ScoreplayerScore =
res.Leaderboard.GetCurrentPlayerScore(UM_TimeSpan.ALL_TIME, UM_CollectionType.GLOBAL);
if (playerScore != null) {
Debug.Log("Score submitted, new player high score: " +
playerScore.LongScore);
}
} else {
Debug.Log("Score submission failed: " + res.Error.Code + " / " +
res.Error.Description);
}

Initializing Play Games Services

using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;

PlayGamesPlatform.Activate();

Signing In

using GooglePlayGames;
using UnityEngine.SocialPlatforms;
...
// authenticate user:
Social.localUser.Authenticate((bool success) => {
// handle success or failure
});

Revealing/Unlocking an Achievement

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.
Incrementing an Achievement

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
});

Posting a Score to the leaderboard

using GooglePlayGames;
using UnityEngine.SocialPlatforms;
...
// post score 12345 to leaderboard ID "Cfji293fjsie_QA")
Social.ReportScore(12345, "Cfji293fjsie_QA", (bool success) => {
// handle success or failure
});

Showing Achievement UI

using GooglePlayGames;
using UnityEngine.SocialPlatforms;
...
// show achievements UI
Social.ShowAchievementsUI();

Showing Leaderboard UI

using GooglePlayGames;
using UnityEngine.SocialPlatforms;
...
// show leaderboard UI
Social.ShowLeaderboardUI();

S-ar putea să vă placă și