Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, May 12, 2016

Determine if device is an Amazon/Fire TV in Unity 3D

Often when you use the same apk for google play and amazon stores and you need to determine at run time whether your device is running Android OS or a Kindle on Fire OS. You may need to even further determine if the device is an Amazon Fire TV or Android TV app.

In Unity3D you can often use SystemInfo.deviceModel, and put it into if/then or case and set appropriate flags. Then you can implement google play, game circle, forward to the appropriate store for rating an app, etc.:

public static string getDevice() {
if (  SystemInfo.deviceModel.ToLower().Contains("aftb")) {
isAmazon = true;
return "Fire TV";
}
        if (  SystemInfo.deviceModel.ToLower().Contains("amazon")) {
isAmazon = true;
return SystemInfo.deviceModel;
}
isAmazon = false;
return SystemInfo.deviceModel;
}

Tuesday, April 26, 2016

Creating a MusicController Module in Unity 3D C#

In Unity3D or any game engine you sometimes need music to play across multiple scenes. To accomplish this in Unity3D you need to create a MusicController GameObject that doesn't destroy on load. Below I do this with a Singleton Class that retains from scene to scene! Game.music is a static boolean field that tells rest of the system that music is enabled. On this controller I have an array of AudioClip[]. which I can have songs in ogg or mp3 format.




using UnityEngine;
using System.Collections;
using System;
using System.IO;
using Prime31;

public class MusicController : MonoBehaviour {

#region Music
public static MusicController Instance { get; private set; }
public AudioClip[] Tracks;
int currentTrack=0;
public void Awake() {
if (!Game.music) {
Instance = null;
Destroy(gameObject);
return;
}
if (Instance!=null) {
Destroy(gameObject);
GetComponent<AudioSource>().Stop();
}
if (Instance==null) {
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
public string trackName() {
string x = "";
if (GetComponent<AudioSource>().clip!=null)
x = GetComponent<AudioSource>().clip.name;
return x;
}

public void playRandomTrack(bool t) {

GetComponent<AudioSource>().Stop();
GetComponent<AudioSource>().enabled = true;
int x = UnityEngine.Random.Range(0,Tracks.Length);
GetComponent<AudioSource>().clip = Tracks[x];
GetComponent<AudioSource>().Play();
currentTrack = x;
if (GUI.Instance!=null)
GUI.Instance.ShowTextToast("Track: " + trackName(),5f);
}


public void playRandomTrack() {

playRandomTrack(true);
}

public void Start() {

if (Game.music) {
Instance = null;
playRandomTrack();
Awake();
return;
}
}

public void Update() {

if (!Game.music) {
Instance = null;
Destroy(gameObject);
return;
}

if (!GetComponent<AudioSource>().isPlaying && GetComponent<AudioSource>().clip!=null)

playRandomTrack();
if (Game.gameOver) {
GetComponent<AudioSource>().volume = 0.75f;
} else if (Game.shouldBegin)  {
GetComponent<AudioSource>().volume = 0.25f;
} else GetComponent<AudioSource>().volume = 0.75f;
}
#endregion

}

Saturday, January 30, 2016

Observer Pattern in Unity3D's C#

Can't tell you how often I use observers, and delegates and events in C# when using Unity3D. Say you have a boolean value called isWinner in your Game Class. If you want to see if that bool value has became true in a different class you need to subscribe using an observer and observable. Since isWinner is boolean, a different class called Leaderboards needs to run a method that increments a GameCenter leaderboard. You accomplish this through the Observer Pattern and Delegates.

In a Game class:

private static bool _isWinner = false;
public static bool isWinner {
get { return _isWinner; }
set { _isWinner = value;
if (_isWinner) {
initiateWinner();
}
}
}

public delegate void Winner();
public static event Winner initiateWinner;

        public static void finishGame() {
                 isWinner = true;
        }

In a Leaderboard class:

void OnEnable() {
Game.initiateWinner += doWin;
}

void OnDisable() {
Game.initiateWinner -= doWin;
}

void doWin() {
                // do your gamecenter, social, prime31 code here
}


From above it's easy to assess that is happening. isWinner is changed, and the event initateWinner() is initiated. Then on the Leaderboard class it's observed and calls doWin();.

Tuesday, January 19, 2016

Lazy Initialization of Singleton in C# Unity

Singleton's are bad design patterns because they are essentially global variables or static classes vs individually static variables. Though we are taught to stay away from them in gaming they can come in handy, especially in Unity. I usually make my GameControllers singleton because there is essentially no chance that I'd need more than once instance of it.

Lazy initialization is nice because it'll initialize your instance when you need it, as you need it in the lifetime of your class.

As follows:

using UnityEngine;
using System.Collections;
using System;
using System.IO;
using Prime31;

public class GameController : Game {
public static GameController Instance { get; private set; }

#region Unity Behaviour
public void Awake () {
Instance = this;
        }
#endregion

}

You can design the class to inherit attributes (as mine does above from the Abstract Game Class). To reference the class from external classes you'd use GameController.Instance.*.  To access the internal variables when you use this Singleton you'll have to declare them as public.  In lieu of making public variables it's Ideally best to make them private and use getters and setters.

You can also pass Singleton's into methods and functions if you say for arguments sake have 2 classes inheriting from Game, both Singletons. You can decide which Singleton you want to pass in runtime, granted that both classes have the same method "someMethod()" in them publically. This can be done in runtime as follows:

     public void callMethod(Game p) {
         p.someMethod();
     }

    public void test() {
         callMethod(GameController.Instance);
    }

Though many argue Singleton is arguably an Anti-pattern, you can make the counter argument because of the usefulness and ubiquity of rampant use, it's legitimate in any programmer's arsenal.

Thursday, January 16, 2014

Unity3D C# Enemy Find nearest Player Script

In this script which you attach to the Enemy Objects, you may find the nearest object Tagged "Player". The Enemy faces the Player, and chases within a proximity, with a given frequency. See below:

/// <summary>
/// AI character controller.
/// Just A basic AI Character controller
/// will looking for a Target and moving to and Attacking
/// </summary>

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(CharacterSystem))]

public class AICharacterController : MonoBehaviour {

    public GameObject ObjectTarget;
    public string TargetTag = "Player";
    private CharacterSystem character;
    private int aiTime = 0;
    private float scanFrequency = 1.0f;
    private int aiState = 0;

    void Start () {
        character = gameObject.GetComponent<CharacterSystem>();
        InvokeRepeating ("ScanForTarget",0,scanFrequency);
    }
   
    void ScanForTarget() {
        ObjectTarget = GetNearestTaggedObject();
    }

    public GameObject GetNearestTaggedObject () {
        var nearestDistanceSqr = Mathf.Infinity;
        GameObject nearestObj = null;

        foreach (var obj in GameObject.FindGameObjectsWithTag(TargetTag)) {

            var objectPos = obj.transform.position;
            var distanceSqr = (objectPos - transform.position).sqrMagnitude;
           
            if (distanceSqr < nearestDistanceSqr) {
                nearestObj = obj;
                nearestDistanceSqr = distanceSqr;
            }
        }
        return nearestObj;
    }

    public float DistanceSquaredTo(GameObject source, GameObject target) {
        return Vector3.SqrMagnitude(source.transform.position - target.transform.position);
    }

    void Update () {
            //if (GameObject.Find("CharacterDakota").GetComponent<CharacterStatus>().HP > 0) {
           
        if (GameObject.Find("GameManager").GetComponent<GameManager>().Playing) {

            var direction = Vector3.zero;
            if(aiTime<=0){
                aiState = Random.Range(0,4);
                aiTime = Random.Range(10,100);
            }else{
                aiTime--;
            }
            if(ObjectTarget){
                //ObjectTarget = GameObject.FindGameObjectWithTag(TargetTag);   
                float distance = Vector3.Distance(ObjectTarget.transform.position,this.gameObject.transform.position);
               
                if(distance<=2){
                    transform.LookAt(ObjectTarget.transform.position);
                    if(aiTime<=0){
                        if(aiState == 1){
                            character.Attack();
                        }
                    }
                }else{
                    if(aiState == 1){
                        transform.LookAt(ObjectTarget.transform.position);
                        direction = this.transform.forward;
                        direction.Normalize();
                        character.Move(direction);
                    }
                }
               
            }else{
                ScanForTarget();
            }
        }
    }
}

Friday, May 10, 2013

DateTime in C# return day of week

This simple function in C# returns what day of the week string wtih a simple DateTime variable pushed to it is.


   public string dayOfWeek(DateTime date)
        {
            return date.DayOfWeek.ToString();
        }

Wednesday, March 27, 2013

Change Frame Rate in Unity3D

The FPS framerate in Unity3D is easier than ever with Unity3D 3.5+.

Below is the JS and the C# code counterpart:


    function Awake () {
        // Make the game run as fast as possible in the web player
        Application.targetFrameRate = 300;
    }
public class example : MonoBehaviour {
    void Awake() {
        Application.targetFrameRate = 300;
    }
}

Tuesday, October 2, 2012

Using Social APIs from Unity (Leaderboard)

To submit a high score from your app to the Game Center leaderboard is easy with the Social API:
IN C# put this in your score dialog or .cs code:


void DoLeaderboard () {
    
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);
    
Social.CreateLeaderboard();
if (Application.loadedLevel == 18)
{
Social.CreateLeaderboard().id = "score18";
ReportScore(TotalScore + TotalScore2,"score18");
shown = true;
else if (Application.loadedLevel == 9)
{
Social.CreateLeaderboard().id = "score9";
ReportScore(TotalScore,"score9");
shown = true;
}
Social.ShowLeaderboardUI();
}
    else
        Debug.Log ("Authentication failed");
} );
}

void ReportScore (long score, string leaderboardID) {
    Debug.Log ("Reporting score " + score + " on leaderboard " + leaderboardID);
    Social.ReportScore (score, leaderboardID, success => {
        Debug.Log(success ? "Reported score successfully" : "Failed to report score");
    });
}

Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...