Ejemplo n.º 1
0
    public static void EntryPoint()
    {
        IProgram2.Television television = new IProgram2.Television();
        IElectronicDevice    TV         = TVRemote.GetDevice();
        PowerButton          pb         = new PowerButton(TV);

        pb.Execute();
        pb.Undo();
    }
Ejemplo n.º 2
0
        public void Red_LED_kettle_On()
        {
            Kettle      kettle  = new Kettle();
            PowerButton power   = new PowerButton();
            WarningLED  warning = new WarningLED();

            power.PressedPowerButton(kettle, warning);

            Assert.AreEqual(Color.Red, kettle.LED);
        }
Ejemplo n.º 3
0
        public void kettle_turned_on()
        {
            Kettle      kettle  = new Kettle();
            PowerButton power   = new PowerButton();
            WarningLED  warning = new WarningLED();

            power.PressedPowerButton(kettle, warning);

            Assert.AreEqual(true, kettle.KettelOn);
        }
Ejemplo n.º 4
0
        public void turn_off_a_turned_on_kettle()
        {
            Kettle      kettle      = new Kettle();
            PowerButton powerButton = new PowerButton();
            WarningLED  warning     = new WarningLED();

            powerButton.PressedPowerButton(warning, kettle);
            powerButton.PressedPowerButton(warning, kettle);

            Assert.AreEqual(false, kettle.KettelOn);
        }
Ejemplo n.º 5
0
        public void cannot_turn_on_a_turned_on_kettle()
        {
            Kettle      kettle      = new Kettle();
            PowerButton powerButton = new PowerButton();
            WarningLED  warning     = new WarningLED();

            powerButton.PressedPowerButton(warning, kettle);
            powerButton.PressedPowerButton(warning, kettle);

            Assert.AreNotEqual(true, kettle.KettelOn);
        }
Ejemplo n.º 6
0
 void Start()
 {
     powerbutton = new PowerButton(lights);
     os          = new OS(loadscreen);
     note        = new Note(nodepad, menu, choose, text);
     pictures    = new Pictures(startingscreen, p1, p2, p3);
     google      = new Google(chrom, serf, facade);
     desktop     = new Desktop(screen);
     isOn        = false;
     operation   = false;
 }
Ejemplo n.º 7
0
        public void temperature_cannot_rise_if_there_is_no_liquid_in_the_kettle()
        {
            Kettle      kettle = new Kettle();
            PowerButton power  = new PowerButton();

            kettle.Liquid = null;
            LiquidButton liquid  = new LiquidButton(85);
            WarningLED   warning = new WarningLED();


            power.PressedPowerButton(kettle, warning);
            kettle.Liquid.IncresedLiquidTemperature(kettle, warning);
        }
Ejemplo n.º 8
0
        public void reset_values_when_turn_off()
        {
            Kettle      kettle  = new Kettle();
            PowerButton power   = new PowerButton();
            WarningLED  warning = new WarningLED();

            power.PressedPowerButton(kettle, warning);
            power.PressedPowerButton(kettle, warning);

            Assert.AreEqual(false, kettle.KettelOn);
            Assert.AreEqual(Color.Off, kettle.LED);
            Assert.AreEqual(null, kettle.Liquid);
        }
Ejemplo n.º 9
0
        public void temperature_rise_when_kettle_is_On()
        {
            Kettle      kettle = new Kettle();
            PowerButton power  = new PowerButton();

            kettle.Liquid = new LiquidButton(87);
            WarningLED warning = new WarningLED();

            power.PressedPowerButton(kettle, warning);
            kettle.Liquid.IncresedLiquidTemperature(kettle, warning);
            Assert.AreEqual(true, kettle.KettelOn);
            Assert.AreEqual(97, kettle.Liquid.Temperature);
        }
Ejemplo n.º 10
0
        public override float GetWidgetHeight(SerializedProperty property, FieldInfo fieldInfo)
        {
            if (target == null)
            {
                target = fieldInfo.GetValue(property.serializedObject.targetObject) as PowerButton;
            }

            if (target == null)
            {
                return(EditorGUIUtility.singleLineHeight);
            }
            return(target.height < EditorGUIUtility.singleLineHeight ? EditorGUIUtility.singleLineHeight : target.height);
        }
Ejemplo n.º 11
0
        public void Green_LED_when_temperature_is_over_100()
        {
            Kettle      kettle = new Kettle();
            PowerButton power  = new PowerButton();

            kettle.Liquid = new LiquidButton(87);
            WarningLED warning = new WarningLED();

            power.PressedPowerButton(kettle, warning);
            kettle.Liquid.IncresedLiquidTemperature(kettle, warning);
            kettle.Liquid.IncresedLiquidTemperature(kettle, warning);
            Assert.AreEqual(true, kettle.KettelOn);
            Assert.AreEqual(107, kettle.Liquid.Temperature);
            Assert.AreEqual(Color.Green, kettle.LED);
        }
Ejemplo n.º 12
0
        public void Green_LED_when_temperature_is_over_100()
        {
            Kettle       kettle       = new Kettle();
            PowerButton  powerButton  = new PowerButton();
            LiquidButton liquidButton = new LiquidButton();
            WarningLED   warning      = new WarningLED();

            powerButton.PressedPowerButton(warning, kettle);

            for (int i = 0; i < 9; i++)
            {
                liquidButton.IncresedLiquidTemperature(warning, kettle);
            }

            Assert.AreEqual(Color.Green, kettle.LED);
        }
Ejemplo n.º 13
0
        public void temperature_rise_when_kettle_is_On()
        {
            Kettle       kettle       = new Kettle();
            PowerButton  powerButton  = new PowerButton();
            LiquidButton liquidButton = new LiquidButton();
            WarningLED   warning      = new WarningLED();

            powerButton.PressedPowerButton(warning, kettle);
            liquidButton.IncresedLiquidTemperature(warning, kettle);

            Assert.AreEqual(true, kettle.KettelOn);
            Assert.AreEqual(25, kettle.Temperature);

            liquidButton.IncresedLiquidTemperature(warning, kettle);

            Assert.AreEqual(35, kettle.Temperature);
        }
Ejemplo n.º 14
0
        public void reset_values_when_turn_off()
        {
            Kettle       kettle       = new Kettle();
            PowerButton  powerButton  = new PowerButton();
            LiquidButton liquidButton = new LiquidButton();
            WarningLED   warning      = new WarningLED();

            powerButton.PressedPowerButton(warning, kettle);

            for (int i = 0; i < 9; i++)
            {
                liquidButton.IncresedLiquidTemperature(warning, kettle);
            }

            powerButton.PressedPowerButton(warning, kettle);

            Assert.AreEqual(false, kettle.KettelOn);
            Assert.AreEqual(Color.Off, kettle.LED);
            Assert.AreEqual(15, kettle.Temperature);
        }
Ejemplo n.º 15
0
        private static void Sample2()
        {
            // We are now modeling the act of
            // picking up a remote, aiming it
            // at the TV, clicking the power
            // button and then watching as
            // the TV turns on and off

            // Pick up the TV remote
            IElectronicDevice TV = TvRemote.GetDevice();

            // Create the power button
            PowerButton powBut = new PowerButton(TV);

            // Turn the TV on and off with each
            // press
            powBut.Execute();
            TV.VolumeUp();
            powBut.Undo();
        }
Ejemplo n.º 16
0
        public override void WidgetDrawer(Rect position, SerializedProperty property, FieldInfo fieldInfo, GUIContent label)
        {
            if (target == null)
            {
                target = fieldInfo.GetValue(property.serializedObject.targetObject) as PowerButton;
            }

            if (buttonMethodInfo == null)
            {
                buttonMethodInfo = property.serializedObject.targetObject.GetType().GetMethod(target.handler,
                                                                                              BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Default);
            }

            Color  backgroundColor = GUI.backgroundColor;
            string buttonContent   = target == null ? "Invalid Button" : target.button;

            GUI.backgroundColor = target == null ? Color.red : backgroundColor;

            if (target != null)
            {
                position.height = target.height < EditorGUIUtility.singleLineHeight ? EditorGUIUtility.singleLineHeight : target.height;
            }
            else
            {
                position.height = EditorGUIUtility.singleLineHeight;
            }

            if (GUI.Button(position, buttonContent))
            {
                if (buttonMethodInfo != null)
                {
                    buttonMethodInfo.Invoke(property.serializedObject.targetObject, null);
                }
                else
                {
                    Debug.LogErrorFormat("Button({0}) Callback({1}) Assign Failed!", buttonContent, target.handler);
                }
            }
            GUI.backgroundColor = backgroundColor;
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            var PowerBtn = new PowerButton();

            Console.WriteLine("Started");

            while (true)
            {
                if (PowerBtn.IsPowerButtonPressed())
                {
                    Debug.WriteLine("Power button pressed. Waiting for release.");
                    PowerBtn.PushPowerButton();
                    while (PowerBtn.IsPowerButtonPressed())
                    {
                        Thread.Sleep(10);
                    }

                    Debug.WriteLine("Power button released.");
                    PowerBtn.ReleasePowerButton();
                }
            }
        }
Ejemplo n.º 18
0
    private void FindPowerButton()
    {
        // Find the power button on this surface.
        foreach (Component child in transform)
        {
            if (child.tag == powerButtonTag)
            {
                if (powerButton == null)
                {
                    powerButton = child.gameObject.GetComponent <PowerButton>();
                    Debug.Log("Surface " + gameObject.name + ": power button was found automatically.");
                }
                else
                {
                    Debug.LogWarning("More than one power button detected on surface " + gameObject.name + "; only the first will be used.");
                }
            }
        }

        if (powerButton == null)
        {
            Debug.LogError("Surface " + gameObject.name + " was expected to have a GameObject tagged as " + powerButtonTag);
        }
    }
Ejemplo n.º 19
0
        //this is f*****g awesome 2020
        //this is f*****g awesome 2020
        //This is f*****g awesome 2020-3
        //This is f*****g awesome 2020-4

        static void Main(string[] args)
        {
            Shape[] shapes = { new Circle(5),
                               new Rectangle(4, 5) };

            foreach (Shape s in shapes)
            {
                s.GetInfo();
                Console.WriteLine("{0} Area : {1:f2}",
                                  s.Name, s.Area());

                Circle testCirc = s as Circle;
                if (testCirc == null)
                {
                    Console.WriteLine("this is not circle");
                }

                if (s is Circle)
                {
                    Console.WriteLine("this isn't a Rectangle");
                }
            }

            Vehicle buick = new Vehicle("Buick",
                                        4, 160);

            if (buick is IDrivable)
            {
                buick.Move();
                buick.Stop();
            }
            else
            {
                Console.WriteLine($"The {0} can't be driver",
                                  buick.Brand);
            }

            IElectronicDevice TV = TVRemote.GetDevice();

            PowerButton powBut = new PowerButton(TV);

            powBut.Execute();
            powBut.Undo();

            Console.WriteLine("*************************************************");

            ArrayList aList = new ArrayList();

            aList.Add("Bob");
            aList.Add(40);

            Console.WriteLine(aList.Count);

            Console.WriteLine(aList.Capacity);
            ArrayList aList2 = new ArrayList();

            aList2.AddRange(new Object[] { "mike",
                                           "Sally", "Egg" });

            foreach (Object obj in aList2)
            {
                Console.WriteLine(obj);
            }

            aList.AddRange(aList2);

            foreach (Object obj in aList)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("*************************");
            aList2.Sort();
            aList2.Reverse();

            foreach (Object obj in aList2)
            {
                Console.WriteLine(obj);
            }

            aList2.Insert(1, "suraj");
            Console.WriteLine("*************************");
            foreach (Object obj in aList2)
            {
                Console.WriteLine(obj);
            }
            ArrayList range = aList2.GetRange(0, 2);

            Console.WriteLine("*************************");
            foreach (Object obj in range)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine(range.IndexOf("suraj"));
            string[]  customers     = { "Bob", "Sally", "Sue" };
            ArrayList custArrayList = new ArrayList();

            custArrayList.AddRange(customers);

            foreach (string s in custArrayList)
            {
                Console.WriteLine(s);
            }


            //Dictionary
            Dictionary <string, string> superheroes =
                new Dictionary <string, string>();

            superheroes.Add("pitam bahadur gurung", "surperman");
            superheroes.Add("laxmi prajapati", "wonder women");
            superheroes.Add("suraj gurung", "gas man");

            Console.WriteLine("***********************");

            Console.WriteLine(" Count: {0}", superheroes.Count);

            Console.WriteLine("pitam bahadur gurung: {0}",
                              superheroes.ContainsKey("pitam bahadur gurung"));

            foreach (KeyValuePair <string, string> item in superheroes)
            {
                Console.WriteLine("{0}:{1}",
                                  item.Key,
                                  item.Value);
            }

            //Queue: first in firs out
            Queue queue = new Queue();

            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            queue.Dequeue();

            foreach (object o in queue)
            {
                Console.WriteLine(o);
            }

            object[] numArray = queue.ToArray();

            foreach (object o in numArray)
            {
                Console.WriteLine(o);
            }

            //stack , first in, last out

            Stack stack = new Stack();

            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            Console.WriteLine("Peek 1 : {0}",
                              stack.Peek());
            Console.WriteLine("Contain 1: {0}",
                              stack.Contains(1));

            object[] numArray2 = stack.ToArray();

            Console.WriteLine("****************");

            foreach (Object o in stack)
            {
                Console.WriteLine(o);
            }
            Console.WriteLine("****************");
            foreach (object o in numArray2)
            {
                Console.WriteLine(o);
            }
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            #region Basics

            // Example Single-line Comment

            /* Example
             * Multiline
             * Comment
             */

            //Hello World
            Console.WriteLine("Hello World");

            //Get user input
            Console.Write("What's your name? ");
            string name = Console.ReadLine();
            Console.WriteLine("Hello " + name);

            //Data Types
            bool canVote = true;
            char fumoffu = '%';

            int     maxInt     = int.MaxValue;
            long    maxLong    = long.MaxValue;
            decimal maxDecimal = decimal.MaxValue;
            float   maxFloat   = float.MaxValue;
            double  maxDouble  = double.MaxValue;

            Console.WriteLine("Max Int: " + maxInt);

            //Implicit type variable declaration
            var sampleVar = "SampleString";

            //You can't change its type after declaration though
            //sampleVar = 2;

            Console.WriteLine("sampleVar is a {0}", sampleVar.GetTypeCode());
            Console.WriteLine("-------------------------------------------------------");

            //Arithmetics
            Console.WriteLine("5 + 3 = " + (5 + 3));
            Console.WriteLine("5 - 3 = " + (5 - 3));
            Console.WriteLine("5 * 3 = " + (5 * 3));
            Console.WriteLine("5 / 3 = " + (5 / 3));
            Console.WriteLine("5.2 % 3 = " + (5.2 % 3));

            int i = 0;

            Console.WriteLine("i++ = " + i++);
            Console.WriteLine("++i = " + ++i);
            Console.WriteLine("i-- = " + i--);
            Console.WriteLine("--i = " + --i);

            Console.WriteLine("-------------------------------------------------------");
            //Some Math Static Functions
            //acos, asin, atan, atan2, cos, cosh, exp, log, sin, sinh, tan, tanh
            double num1 = 10.5;
            double num2 = 15;

            Console.WriteLine("Abs(num1): " + Math.Abs(num1));
            Console.WriteLine("Ceiling(num1): " + Math.Ceiling(num1));
            Console.WriteLine("Floor(num1): " + Math.Floor(num1));
            Console.WriteLine("Max(num1, num2): " + Math.Max(num1, num2));
            Console.WriteLine("Min(num1, num2): " + Math.Min(num1, num2));
            Console.WriteLine("Pow(num1): " + Math.Pow(num1, num2));
            Console.WriteLine("Round(num1): " + Math.Round(num1));
            Console.WriteLine("Sqrt(num1): " + Math.Sqrt(num1));

            Console.WriteLine("-------------------------------------------------------");

            //Casting
            const double PI    = 3.14;
            int          intPI = (int)PI;

            //Generating Random Numbers
            Random rand = new Random();
            Console.WriteLine("Random number between 1 and 10: " + rand.Next(1, 11));

            #endregion

            #region Conditionals and Loops

            //Relational Operators: > < >= <= == !=
            //Logical Operators: && (AND) || (OR) ^ (XOR) ! (NOT)

            int age = rand.Next(1, 101);
            Console.WriteLine(age);

            //IF statements
            if (age >= 5 && age <= 7)
            {
                Console.WriteLine("Go to Elementary School");
            }
            else if (age > 7 && age < 13)
            {
                Console.WriteLine("Go to Middle School");
            }
            else
            {
                Console.WriteLine("Go to High School");
            }

            if (age < 14 || age > 67)
            {
                Console.WriteLine("You Shouldn't Work");
            }

            Console.WriteLine("! true: " + !true);

            //Ternary - Condition ? ifTrue : ifFalse
            bool canDrive = age >= 18 ? true : false;

            switch (age)
            {
            case 0:
                Console.WriteLine("Infant");
                break;

            case 1:
            case 2:
                Console.WriteLine("Toddler");
                //Goto jumps to the code block you specify (It's gonna kick you out of the switch statement)
                goto Checkpoint1;

            default:
                Console.WriteLine("Child");
                break;
            }

Checkpoint1:
            Console.WriteLine("I'm printed from outside the switch statement");

            Console.WriteLine("-------------------------------------------------------");

            int j = 0;

            while (j < 10)
            {
                if (j == 7)
                {
                    j++;
                    continue;
                }
                //^^^ Jump back to the while header

                if (j == 9)
                {
                    break;
                }
                //// ^^ Jump out of the loop

                if (j % 2 > 0)
                {
                    Console.WriteLine(j);
                }

                j++;
            }

            Console.WriteLine("-------------------------------------------------------");

            //DO While: The body of do is executed at least one time
            string guess;

            do
            {
                Console.WriteLine("Guess a number");
                guess = Console.ReadLine();
            } while (!guess.Equals("15"));

            Console.WriteLine("-------------------------------------------------------");

            //FOR Loop: All the conditional and counter stuff is in the heading
            for (int k = 0; k < 10; k++)
            {
                if (k % 2 != 0)
                {
                    Console.WriteLine(k);
                }
            }

            Console.WriteLine("-------------------------------------------------------");

            //FOREACH: Used to iterate over list, arrays, maps and collections
            string randString = "Example Random String";

            foreach (char c in randString)
            {
                Console.WriteLine(c);
            }

            Console.WriteLine("-------------------------------------------------------");

            #endregion

            #region Strings & Arrays

            //Strings
            //Escape Sequences: Allow you to enter special chars in strings
            //      \' \" \\ \b \n \t
            string sampleString = "Some random words";

            //Prints wether a string is empty or null
            Console.WriteLine("Is Empty: " + String.IsNullOrEmpty(sampleString));
            //Prints wether a string is null or filled with white space
            Console.WriteLine("Is Empty: " + String.IsNullOrWhiteSpace(sampleString));

            Console.WriteLine("String Length: " + sampleString.Length);
            //Returns the position of a certain string/char inside of another string | returns -1 if it doesn't find it
            Console.WriteLine("Index of 'random': " + sampleString.IndexOf("random"));
            //Returns a substring of the parent string when given the index of the first letter and the length of the word

            Console.WriteLine("2nd word: " + sampleString.Substring(5, 6));
            //Returns true if the parent string is equals to the argument string
            Console.WriteLine("Strings Equal: " + sampleString.Equals(randString));
            //Returns true if the String starts with the argument string

            Console.WriteLine("Starts with \"Example Random\": " + randString.StartsWith("Example Random"));
            //Returns true if the String ends with the argument string
            Console.WriteLine("Ends with \"Example String\": " + randString.EndsWith("Example String"));

            //Removes white space at the beginning or at the end of a string
            sampleString = sampleString.Trim(); //TrimEnd TrimStart

            //Replaces a substring of the parent string with another string
            sampleString = sampleString.Replace("words", "characters");

            //Removes a substring of length equals to the second parameter starting from the passed index (first parameter)
            sampleString = sampleString.Remove(0, 4);

            //Array of strings
            string[] words = new string[6] {
                "I", "Suck", "At", "Drawing", "Textures", ":("
            };
            //Join a string array into one single string
            Console.WriteLine("Joined String Array: " + String.Join(" ", words));

            Console.WriteLine("-------------------------------------------------------");

            //Formatting Strings
            string formatted = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 4.99, 15.567, .56, 1000);
            Console.WriteLine("Formatted Strings examples: " + formatted);

            Console.WriteLine("-------------------------------------------------------");

            //String Builder
            //Used when you want to edit a string without creating a new one
            StringBuilder sb = new StringBuilder();
            //Append new strings - (AppendLine is the version that appends a \n at the end automatically)
            sb.Append("This is the first Sentence.");
            sb.AppendFormat("My Nick is {0} and I am a {1} developer", "Davoleo", "C#");
            //Empties the whole StringBuilder Buffer
            //sb.Clear();
            //Replaces a string with another one in all the occurrences in the StringBuilder
            sb.Replace("e", "E");
            //Removes chars from index 5 (included) to index 7 (excluded)
            sb.Remove(5, 7);
            //Converts the StringBuilder to a String and writes it on the console
            Console.WriteLine(sb.ToString());

            Console.WriteLine("-------------------------------------------------------");

            //Arrays
            int[] randArray;
            int[] randFixedArray = new int[5];
            int[] literalArray   = { 1, 2, 3, 4, 5 };

            //Returns the number of items in the array
            Console.WriteLine("Array Length: " + literalArray.Length);
            //Returns the first item of an array
            Console.WriteLine("First Item: " + literalArray[0]);

            //Loop through arrays

            //Classic For loop with array length
            for (int k = 0; k < literalArray.Length; k++)
            {
                Console.WriteLine("{0} : {1}", k, literalArray[k]);
            }
            //For Each
            foreach (int num in literalArray)
            {
                Console.WriteLine(num);
            }

            //Returns the index of a specific array element
            Console.WriteLine("Index of 3: " + Array.IndexOf(literalArray, 3));

            string[] names = { "Shana", "Alastor", "Wilhelmina", "Decarabia", "Fecor", "Hecate", "Sydonnay" };
            //Joins all the items of an array dividing them with a custom separator
            string nameCollectionString = string.Join(", ", names);

            names = nameCollectionString.Split(',');

            //Multidimensional Arrays
            //Two dimensional empty array of length 5*3
            int[,] multArray = new int[5, 3];

            //Literal Init
            int[,] multArray2 = { { 0, 1 }, { 2, 3 }, { 4, 5 } };

            foreach (int num in multArray2)
            {
                Console.WriteLine(num);
            }

            Console.WriteLine("-------------------------------------------------------");

            //Lists: Dynamic Arrays
            List <int> numList = new List <int>();

            //Adds a Single item to the list
            numList.Add(5);
            numList.Add(15);
            numList.Add(25);

            //Adds a range of items to the list (in some kind of collection form)
            int[] numArray = { 1, 2, 3, 4 };
            numList.AddRange(numArray);

            //Removes All the items in the list
            //numList.Clear();

            //Init a list with an array (aka create a list from an array)
            List <int> numList2 = new List <int>(numArray);

            //Insert an item in a specific index
            numList.Insert(1, 10);

            //Removes the first occurance of the argument in the list, from the list
            numList.Remove(5);
            //Removes the item at the index 2
            numList.RemoveAt(2);

            for (var l = 0; l < numList.Count; l++)
            {
                Console.WriteLine(numList[l]);
            }

            //Returns the index of the first occurance of the passed item (returns -1 if it doesn't find any)
            Console.WriteLine("4 is in index " + numList2.IndexOf(4));

            Console.WriteLine("is 5 in the list " + numList.Contains(5));

            List <string> stringList = new List <string>(new string[] { "Davoleo", "Matpac", "Pierknight" });
            //case insensitive String comparison
            Console.WriteLine("Davoleo in list " + stringList.Contains("davoleo", StringComparer.OrdinalIgnoreCase));

            //Sorts the list alphabetically or numerically depending on the contents
            numList.Sort();

            Console.WriteLine("-------------------------------------------------------");

            #endregion

            #region Exceptions

            //Exception Handling
            //Try and Catch Structure
            try
            {
                Console.Write("Divide 10 by ");
                int num = int.Parse(Console.ReadLine());
                Console.WriteLine("10/{0} = {1}", num, 10 / num);
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Can't divide by 0");
                //Prints the name of the exception
                Console.WriteLine(e.GetType().Name);
                //Prints a small description of the exception
                Console.WriteLine(e.Message);
                //Throws the same exception again
                //throw e;
                //Throws another new Exception
                throw new InvalidOperationException("Operation Failed", e);
            }
            catch (Exception e)
            {
                //This Catches all the exceptions
                Console.WriteLine(e.GetType().Name);
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("-------------------------------------------------------");

            #endregion

            #region OOP

            //Classes and Objects
            Animal botolo = new Animal(0.5, 6, "Meeer", "Botolo");

            Console.WriteLine("{0} says {1}", botolo.Name, botolo.Sound);
            Console.WriteLine(botolo.ToString());
            Console.WriteLine(Animal.GetCount());

            Console.WriteLine("-------------------------------------------------------");

            //Method Overloading test
            //This Calls the int version
            Console.WriteLine("1 + 25 = " + GetSum(1, 25));
            //This Calls the double version
            //Passing parameters in another order
            Console.WriteLine("7.64 + 9.24 = " + GetSum(num2: 7.64, num1: 9.24));

            Console.WriteLine("-------------------------------------------------------");

            //Object Initializer - Assigning values to the fields manually
            Animal epicAnimal = new Animal()
            {
                Name   = "Grover",
                Height = 13,
                Weight = 11,
                Sound  = "GRRR"
            };
            Console.WriteLine(epicAnimal.ToString());

            Console.WriteLine("-------------------------------------------------------");
            //Polymorphism
            Shape rect   = new Rectangle(5, 8);
            Shape tri    = new Triangle(8, 3);
            Shape circle = new Circle(5);

            //Array of different kinds of shapes
            Shape[] shapeArray = { rect, tri, circle };

            foreach (var shape in shapeArray)
            {
                shape.LogShapeInfo();
            }
            Console.WriteLine("***");

            Console.WriteLine("Rect Area: " + rect.Area());
            Console.WriteLine("Tri Area: " + tri.Area());
            Console.WriteLine("Circle Area: " + circle.Area());
            Console.WriteLine("tri is a Triangle: " + (tri is Triangle));
            Console.WriteLine("rect is a Rectangle: " + ((rect as Rectangle) != null));
            Console.WriteLine("-------------------------------------------------------");

            //Operator Overloading for objects
            Rectangle combinedRectangle = new Rectangle(6, 10) + (Rectangle)rect;
            Console.WriteLine("combinedRectangle Area: " + combinedRectangle.Area());

            Console.WriteLine("-------------------------------------------------------");

            //Interfaces
            IElettronicDevice TV          = TVRemote.GetDevice();
            PowerButton       powerButton = new PowerButton(TV);
            powerButton.Execute();
            powerButton.Undo();

            Console.WriteLine("-------------------------------------------------------");

            //Generics - Classes that can be used with any kind of object
            SimpleMapEntry <int, string> davPass = new SimpleMapEntry <int, string>(333, "Davoleo");

            davPass.ShowData();

            //Generics work with multiple data types
            int firstInt = 5, secondInt = 4;
            GetSum(ref firstInt, ref secondInt);
            string firstString  = firstInt.ToString();
            string secondString = secondInt.ToString();
            GetSum(ref firstString, ref secondString);

            Rectangle <int> rect1 = new Rectangle <int>(20, 50);
            Console.WriteLine(rect1.GetArea());
            Rectangle <string> rect2 = new Rectangle <string>("20", "50");
            Console.WriteLine(rect2.GetArea());

            Console.WriteLine("-------------------------------------------------------");

            Temperature waveTemp = Temperature.WARM;

            switch (waveTemp)
            {
            case Temperature.FREEZE:
                Console.WriteLine("Freezing Temperature");
                break;

            case Temperature.LOW:
                Console.WriteLine("Low Temperature");
                break;

            case Temperature.WARM:
                Console.WriteLine("Warm Temperature");
                break;

            case Temperature.HOT:
                Console.WriteLine("Hot Temperature");
                break;

            case Temperature.SEARING:
                Console.WriteLine("EPIC Temperature, everything Sublimates");
                break;

            default:
                Console.WriteLine("Invalid Temperature");
                break;
            }

            Console.WriteLine("-------------------------------------------------------");

            //STRUCTS
            Customer davoleo = new Customer();
            davoleo.createCustomer("Davoleo", 55.80, 111);
            davoleo.printInfo();

            Console.WriteLine("-------------------------------------------------------");
            //DELEGATES - Passing methods to other methods as parameters

            //Anonymous method of type EvaluateExpression
            EvaluateExpression add = delegate(double n1, double n2) { return(n1 + n2); };
            //Direct Delegate Assignment
            EvaluateExpression substract = (n1, n2) => { return(n1 + n2); };
            EvaluateExpression multiply  = delegate(double n1, double n2) { return(n1 * n2); };

            //Calls both the delegates
            EvaluateExpression subtractMultuply = substract + multiply;

            Console.WriteLine("5 + 10 = " + add(5, 10));
            Console.WriteLine("5 * 10 = " + multiply(5, 10));
            Console.WriteLine("Subtract & Multiply 10 & 4: " + subtractMultuply(10, 4));

            //Lamda expressions - Anonymous functions
            Func <int, int, int> subtract = (x, y) => x - y;
            Console.WriteLine("5 - 10 = " + subtract.Invoke(5, 10));

            List <int> nums = new List <int> {
                3, 6, 9, 12, 15, 18, 21, 24, 27, 30
            };
            List <int> oddNumbers = nums.Where((n) => n % 2 == 1).ToList();

            foreach (var oddNumber in oddNumbers)
            {
                Console.Write(oddNumber + ", ");
            }
            Console.WriteLine();
            Console.WriteLine("-------------------------------------------------------");

            #endregion


            #region File IO

            //File I/O
            //Access the current directory
            DirectoryInfo dir    = new DirectoryInfo(".");
            DirectoryInfo davDir = new DirectoryInfo(@"C:\Users\Davoleo");

            Console.WriteLine("Davoleo path: " + davDir.FullName);
            Console.WriteLine("Davoleo dir name " + davDir.Name);
            Console.WriteLine(davDir.Parent);
            Console.WriteLine(davDir.Attributes);
            Console.WriteLine(davDir.CreationTime);

            //Creates a directory
            Directory.CreateDirectory(@"D:\C#Data");
            DirectoryInfo dataDir = new DirectoryInfo(@"D:\C#Data");
            //Directory.Delete(@"D:\C#Data");
            string dataPath = @"D:\C#Data";
            Console.WriteLine("-------------------------------------------------------");

            string[] nicks = { "Davoleo", "Matpac", "Pierknight", "gesudio" };

            using (StreamWriter writer = new StreamWriter("nicknames.txt"))
            {
                foreach (var nick in nicks)
                {
                    writer.WriteLine(nick);
                }
            }

            using (StreamReader reader = new StreamReader("nicknames.txt"))
            {
                string user;
                while ((user = reader.ReadLine()) != null)
                {
                    Console.WriteLine(user);
                }
            }

            //Another Way of writing and reading
            File.WriteAllLines(dataPath + "\\nicknames.txt", nicks);
            Console.WriteLine(File.ReadAllBytes(dataPath + "\\nicknames.txt").ToString());

            FileInfo[] textFiles = dataDir.GetFiles("*.txt", SearchOption.AllDirectories);
            Console.WriteLine("Matches: {0}" + textFiles.Length);

            Console.WriteLine(textFiles[0].Name + ", " + textFiles[0].Length);

            string     fileStreamPath   = @"D:\C#Data\streamtest.txt";
            FileStream stream           = File.Open(fileStreamPath, FileMode.Create);
            string     randomString     = "This is a random String";
            byte[]     randomStringByte = Encoding.Default.GetBytes(randString);
            stream.Write(randomStringByte, 0, randomStringByte.Length);
            stream.Position = 0;
            stream.Close();

            string       binaryPath   = @"D:\C#Data\file.dat";
            FileInfo     datFile      = new FileInfo(binaryPath);
            BinaryWriter binaryWriter = new BinaryWriter(datFile.OpenWrite());
            string       text         = "Random Text";
            age = 18;
            double height = 12398;

            binaryWriter.Write(text);
            binaryWriter.Write(age);
            binaryWriter.Write(height);

            binaryWriter.Close();

            BinaryReader binaryReader = new BinaryReader(datFile.OpenRead());
            Console.WriteLine(binaryReader.ReadString());
            Console.WriteLine(binaryReader.ReadInt32());
            Console.WriteLine(binaryReader.ReadDouble());

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            //OOP Game test
            Warrior maximus = new Warrior("Maximus", 1000, 120, 40);
            Warrior bob     = new Warrior("Bob", 1000, 120, 40);

            Console.WriteLine("Disabled");
            //Battle.StartFight(maximus, bob);

            Console.WriteLine("-------------------------------------------------------");

            //Collections ----

            #region ArrayList

            //You can add different kind of objects ArrayLists
            ArrayList arrayList = new ArrayList();
            arrayList.Add("Bob");
            arrayList.Add(43);

            //Number of items in the arraylist
            Console.WriteLine("ArrayList Count: " + arrayList.Count);
            //Capacity is always double the count (?)
            Console.WriteLine("ArrayList Capacity: " + arrayList.Capacity);

            ArrayList arrayList2 = new ArrayList();
            //Add an array to the ArrayList
            arrayList2.AddRange(new object[] { "Jeff", "Dave", "Egg", "Edge" });

            arrayList.AddRange(arrayList2);

            //Sort items in natural order
            arrayList2.Sort();
            //Reverse the order of items
            arrayList2.Reverse();

            //Insert some item at a specific index
            arrayList2.Insert(1, "PI");

            //Sub-Arraylist made of some of the items in the original arraylist
            ArrayList range = arrayList2.GetRange(0, 2);

            Console.WriteLine("arrayList object ---");
            foreach (object o in arrayList)
            {
                Console.Write(o + "\t");
            }
            Console.WriteLine();

            Console.WriteLine("arrayList2 object ---");
            foreach (object o in arrayList2)
            {
                Console.Write(o + "\t");
            }
            Console.WriteLine();

            Console.WriteLine("range object ----");
            foreach (object o in range)
            {
                Console.Write(o + "\t");
            }
            Console.WriteLine();

            //Remove the item at the 0 index
            //arrayList2.RemoveAt(0);

            //Removes the first 2 items starting from index 0
            //arrayList2.RemoveRange(0, 2);

            //Return the index of a specific object - if it doesn't find any it returns -1
            Console.WriteLine("Index of Edge: " + arrayList2.IndexOf("Edge"));

            //Converting ArrayLists to arrays
            string[] array = (string[])arrayList2.ToArray(typeof(string));

            //Converting back to Arraylist
            ArrayList listFromArray = new ArrayList(array);

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Dictionary

            //Stores a list of key-value pairs
            Dictionary <string, string> langsProjs = new Dictionary <string, string>();

            //Add A Key-Value Pair
            langsProjs.Add("C#", "CSharp-Test");
            langsProjs.Add("Java", "Metallurgy 4: Reforged");
            langsProjs.Add("Dart", "sample_flutter_app");

            //Removes a Pair from a given key
            langsProjs.Remove("Dart");

            //Number of pairs in the list
            Console.WriteLine("Count: " + langsProjs.Count);

            //Returns wether a key is present
            Console.WriteLine("C# is present: " + langsProjs.ContainsKey("C#"));

            //Gets the value of Java and outputs into a new string called test
            langsProjs.TryGetValue("Java", out string test);
            Console.WriteLine("Java: " + test);

            //Loop over all the pairs in the list
            Console.WriteLine("LOOP:");
            foreach (KeyValuePair <string, string> pair in langsProjs)
            {
                Console.WriteLine($"{pair.Key} - {pair.Value}");
            }

            //Empties the dictionary Completely
            langsProjs.Clear();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Queue

            //Creates a new Empty Queue
            Queue queue = new Queue();

            //Adds an item to the queue
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);

            //Loop over a queue
            foreach (object num in queue)
            {
                Console.Write(num + "\t");
            }
            Console.WriteLine();

            Console.WriteLine("is 3 in the queue: " + queue.Contains(3));

            //Removes the first item and return it to you
            Console.WriteLine("Removes 1: " + queue.Dequeue());

            //Returns the first item in the queue without removing it
            Console.WriteLine("Peek the firs num: " + queue.Peek());

            //Empties the queue
            queue.Clear();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Stack

            Stack stack = new Stack();

            //Adds an item to the stack
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            stack.Push(4);

            //Loop over a stack - items are returned in the opposite order
            foreach (var item in stack)
            {
                Console.WriteLine($"Item: {item}");
            }

            //Returns the last item in the stack without removing it
            Console.WriteLine(stack.Peek());

            //Returns the last item in the stack removing it
            Console.WriteLine(stack.Pop());

            //Returns wether the stack contains an item or not
            Console.WriteLine(stack.Contains(3));

            //Convert to an array and print it with the Join function
            Console.WriteLine(string.Join(", ", stack.ToArray()));

            //Empties the stack
            stack.Clear();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region LINQ EXTENSION METHODS
            //LINQ EXTENSION METHODS

            //Lamdas with Delegates
            Console.WriteLine("-- Lambda Expressions --");
            doubleIt doubleIt = x => x * 2;
            Console.WriteLine($"5 * 2 = {doubleIt(5)}");

            List <int> numberList = new List <int> {
                1, 9, 2, 6, 3
            };

            //.Where() METHOD
            var evenList = numberList.Where(a => a % 2 == 0).ToList();
            foreach (var k in evenList)
            {
                Console.Write(k + ", ");
            }
            Console.WriteLine();

            //2nd Example of .Where()
            var rangeList = numberList.Where(x => x > 2 && x < 9).ToList();
            foreach (var k in rangeList)
            {
                Console.Write(k + ", ");
            }
            Console.WriteLine();

            //Coin flips (T = 0 or C = 1)
            List <int> coinFlips = new List <int>();
            int        flips     = 0;
            while (flips < 100)
            {
                coinFlips.Add(rand.Next(0, 2));
                flips++;
            }
            //Count method with predicate
            Console.WriteLine($"Testa Count: {coinFlips.Count(a => a == 0)}");
            Console.WriteLine($"Croce Count: {coinFlips.Count(a => a == 1)}");

            //.Select() METHOD
            var oneToTen = new List <int>();
            oneToTen.AddRange(Enumerable.Range(1, 10));
            var squares = oneToTen.Select(x => x * x);

            foreach (var k in squares)
            {
                Console.Write(k + ", ");
            }
            Console.WriteLine();

            //.Zip() METHOD
            var listOne = new List <int> {
                1, 3, 4
            };
            var listTwo = new List <int> {
                4, 6, 8
            };
            var sumList = listOne.Zip(listTwo, (l1Value, l2Value) => l1Value + l2Value);
            foreach (var k in sumList)
            {
                Console.Write(k + ", ");
            }
            Console.WriteLine();

            //.Aggregate() METHOD
            var nums1to5 = new List <int> {
                1, 2, 3, 4, 5
            };
            Console.WriteLine("Sum of elements {0}", nums1to5.Aggregate((a, b) => a + b));

            //.AsQueryable.Average() Method
            Console.WriteLine($"Average: {nums1to5.AsQueryable().Average()}");
            //.All()
            Console.WriteLine($"All > 3 nums? {nums1to5.All(x => x > 3)}");
            //.Any()
            Console.WriteLine($"Any num > 3? {nums1to5.Any(x => x > 3)}");

            //.Distinct()
            var listWithDupes = new List <int> {
                1, 2, 3, 2, 3
            };
            Console.WriteLine($"Distinct: {string.Join(", ", listWithDupes.Distinct())}");

            //.Except() - Prints all the values that don't exist in the second list
            Console.WriteLine($"Except: {string.Join(", ", nums1to5.Except(listWithDupes))}");

            //.Intersect() - Returns a list with common values between two lists
            Console.WriteLine($"Intersect: {string.Join(", ", nums1to5.Intersect(listWithDupes))}");

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Custom Collection Class

            AnimalFarm animals = new AnimalFarm();
            animals[0] = new Animal("Wilbur");
            animals[1] = new Animal("Templeton");
            animals[2] = new Animal("Wally");
            animals[3] = new Animal("ooooooooooooooooooooooooeuf");

            foreach (Animal animal in animals)
            {
                Console.WriteLine(animal.Name);
            }

            Box box1 = new Box(2, 3, 4);
            Box box2 = new Box(5, 6, 7);


            Box boxSum = box1 + box2;
            Console.WriteLine($"Box Sum: {boxSum}");

            Console.WriteLine($"Box -> Int: {(int) box1}");
            Console.WriteLine($"Int -> Box: {(Box) 4}");

            //Anonymous type object
            var anonymous = new
            {
                Name   = "Mr Unknown",
                Status = 312
            };

            Console.WriteLine("{0} status is {1}", anonymous.Name, anonymous.Status);

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region LINQ

            //Stands for Launguage Integrated Query - Provides tools to work with data
            QueryStringArray();

            QueryIntArray();

            QueryArrayList();

            QueryCollection();

            QueryAnimalData();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Threads

            //Threading allows to execute operation on a different workflow instead of the Main one
            //The workflow continuously and quickly changes thread to

            Thread thread = new Thread(Print1);
            thread.Start();

            for (int k = 0; k < 1000; k++)
            {
                Console.Write(0);
            }
            Console.WriteLine();

            int counter = 1;
            for (int k = 0; k < 10; k++)
            {
                Console.WriteLine(counter);
                //Slow down the current thread of some time in ms
                Thread.Sleep(500);
                counter++;
            }
            Console.WriteLine("Thread Ended");

            BankAccount account = new BankAccount(10);
            Thread[]    threads = new Thread[15];

            Thread.CurrentThread.Name = "main";

            for (int k = 0; k < threads.Length; k++)
            {
                Thread smolThread = new Thread(account.IssueWidthDraw);
                smolThread.Name = k.ToString();
                threads[k]      = smolThread;
            }

            foreach (var smolThread in threads)
            {
                Console.WriteLine("Thread {0} Alive: {1}", smolThread.Name, smolThread.IsAlive);
                smolThread.Start();
                Console.WriteLine("Thread {0} Alive: {1}", smolThread.Name, smolThread.IsAlive);
            }

            Console.WriteLine("Current Priority: " + Thread.CurrentThread.Priority);
            Console.WriteLine($"Thread {Thread.CurrentThread.Name} Ending");

            // Passing data to threads through lambda expressions
            new Thread(() =>
            {
                countTo(5);
                countTo(8);
            }).Start();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Serialization

            Animal dummyDum    = new Animal(45, 25, "Roar", "Dum");
            Stream dummyStream = File.Open("AnimalData.dat", FileMode.Create);

            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(dummyStream, dummyDum);
            dummyStream.Close();

            dummyDum = null;

            dummyStream     = File.Open("AnimalData.dat", FileMode.Open);
            binaryFormatter = new BinaryFormatter();

            dummyDum = (Animal)binaryFormatter.Deserialize(dummyStream);
            dummyStream.Close();

            Console.WriteLine("Dummy Dum from binary: " + dummyDum.ToString());

            dummyDum.Weight = 33;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Animal));

            using (TextWriter tw = new StreamWriter(@"D:\C#Data\dummy-dum.xml"))
            {
                xmlSerializer.Serialize(tw, dummyDum);
            }

            dummyDum = null;

            XmlSerializer xmlDeserializer = new XmlSerializer(typeof(Animal));
            TextReader    txtReader       = new StreamReader(@"D:\C#Data\dummy-dum.xml");
            object        obj             = xmlDeserializer.Deserialize(txtReader);
            dummyDum = (Animal)obj;
            txtReader.Close();

            Console.WriteLine("Dummy Dum from XML: " + dummyDum.ToString());

            #endregion
        }
Ejemplo n.º 21
0
        void OnEnable()
        {
            // Get power component
            powerJoystick = GetComponent <PowerJoystick> ();
            powerDPad     = GetComponent <PowerDPad> ();
            powerButton   = GetComponent <PowerButton> ();
            if (powerJoystick != null)
            {
                powerType = PowerType.Joystick;
            }
            else if (powerDPad != null)
            {
                powerType = PowerType.DPad;
            }
            else if (powerButton != null)
            {
                powerType = PowerType.Button;
            }

            // Subscribe to trigger events
            if (powerType == PowerType.Joystick)
            {
                PowerJoystick.OnJoyPosHTriggerButtonDown += PosHTriggerButtonDown;
                PowerJoystick.OnJoyPosHTriggerButtonUp   += PosHTriggerButtonUp;
                PowerJoystick.OnJoyNegHTriggerButtonDown += NegHTriggerButtonDown;
                PowerJoystick.OnJoyNegHTriggerButtonUp   += NegHTriggerButtonUp;
                PowerJoystick.OnJoyPosVTriggerButtonDown += PosVTriggerButtonDown;
                PowerJoystick.OnJoyPosVTriggerButtonUp   += PosVTriggerButtonUp;
                PowerJoystick.OnJoyNegVTriggerButtonDown += NegVTriggerButtonDown;
                PowerJoystick.OnJoyNegVTriggerButtonUp   += NegVTriggerButtonUp;
            }
            if (powerType == PowerType.DPad)
            {
                PowerDPad.OnDPadPosHTriggerButtonDown += PosHTriggerButtonDown;
                PowerDPad.OnDPadPosHTriggerButtonUp   += PosHTriggerButtonUp;
                PowerDPad.OnDPadNegHTriggerButtonDown += NegHTriggerButtonDown;
                PowerDPad.OnDPadNegHTriggerButtonUp   += NegHTriggerButtonUp;
                PowerDPad.OnDPadPosVTriggerButtonDown += PosVTriggerButtonDown;
                PowerDPad.OnDPadPosVTriggerButtonUp   += PosVTriggerButtonUp;
                PowerDPad.OnDPadNegVTriggerButtonDown += NegVTriggerButtonDown;
                PowerDPad.OnDPadNegVTriggerButtonUp   += NegVTriggerButtonUp;
            }
            // Subscribe to normal button events
            if (powerType == PowerType.Button)
            {
                PowerButton.OnPowerButtonDown += OnPowerButtonDown;
                PowerButton.OnPowerButtonUp   += OnPowerButtonUp;
            }

            // Register joystick axis
            if (powerType == PowerType.Joystick)
            {
                if (powerJoystick.useAxis == PowerJoystick.UseAxis.Both || powerJoystick.useAxis == PowerJoystick.UseAxis.Horizontal)
                {
                    if (powerJoystick.GetHorizontalAxisName() != "" && !CrossPlatformInputManager.AxisExists(powerJoystick.GetHorizontalAxisName()))
                    {
                        horizontalAxis = new CrossPlatformInputManager.VirtualAxis(powerJoystick.GetHorizontalAxisName());
                        CrossPlatformInputManager.RegisterVirtualAxis(horizontalAxis);
                    }
                    // Unregister doesn't work correctly / Get axis reference (necessary if joysticks gets disbled and enabled again)
                    if (powerJoystick.GetHorizontalAxisName() != "" && CrossPlatformInputManager.AxisExists(powerJoystick.GetHorizontalAxisName()))
                    {
                        horizontalAxis = CrossPlatformInputManager.VirtualAxisReference(powerJoystick.GetHorizontalAxisName());
                    }
                }
                if (powerJoystick.useAxis == PowerJoystick.UseAxis.Both || powerJoystick.useAxis == PowerJoystick.UseAxis.Vertical)
                {
                    if (powerJoystick.GetVerticalAxisName() != "" && !CrossPlatformInputManager.AxisExists(powerJoystick.GetVerticalAxisName()))
                    {
                        verticalAxis = new CrossPlatformInputManager.VirtualAxis(powerJoystick.GetVerticalAxisName());
                        CrossPlatformInputManager.RegisterVirtualAxis(verticalAxis);
                    }
                    // Unregister doesn't work correctly / Get axis reference (necessary if joysticks gets disbled and enabled again)
                    if (powerJoystick.GetVerticalAxisName() != "" && CrossPlatformInputManager.AxisExists(powerJoystick.GetVerticalAxisName()))
                    {
                        verticalAxis = CrossPlatformInputManager.VirtualAxisReference(powerJoystick.GetVerticalAxisName());
                    }
                }
            }

            // Register d-pad axis
            if (powerType == PowerType.DPad)
            {
                if (powerDPad.useAxis == PowerDPad.UseAxis.Both || powerDPad.useAxis == PowerDPad.UseAxis.Horizontal)
                {
                    if (powerDPad.GetHorizontalAxisName() != "" && !CrossPlatformInputManager.AxisExists(powerDPad.GetHorizontalAxisName()))
                    {
                        horizontalAxis = new CrossPlatformInputManager.VirtualAxis(powerDPad.GetHorizontalAxisName());
                        CrossPlatformInputManager.RegisterVirtualAxis(horizontalAxis);
                    }
                    // Unregister doesn't work correctly / Get axis reference (necessary if d-pad gets disbled and enabled again)
                    if (powerDPad.GetHorizontalAxisName() != "" && CrossPlatformInputManager.AxisExists(powerDPad.GetHorizontalAxisName()))
                    {
                        horizontalAxis = CrossPlatformInputManager.VirtualAxisReference(powerDPad.GetHorizontalAxisName());
                    }
                }
                if (powerDPad.useAxis == PowerDPad.UseAxis.Both || powerDPad.useAxis == PowerDPad.UseAxis.Vertical)
                {
                    if (powerDPad.GetVerticalAxisName() != "" && !CrossPlatformInputManager.AxisExists(powerDPad.GetVerticalAxisName()))
                    {
                        verticalAxis = new CrossPlatformInputManager.VirtualAxis(powerDPad.GetVerticalAxisName());
                        CrossPlatformInputManager.RegisterVirtualAxis(verticalAxis);
                    }
                    // Unregister doesn't work correctly / Get axis reference (necessary if d-pad gets disbled and enabled again)
                    if (powerDPad.GetVerticalAxisName() != "" && CrossPlatformInputManager.AxisExists(powerDPad.GetVerticalAxisName()))
                    {
                        verticalAxis = CrossPlatformInputManager.VirtualAxisReference(powerDPad.GetVerticalAxisName());
                    }
                }
            }

            // Register button
            if (powerType == PowerType.Button)
            {
                if (powerButton.GetButtonName() != null)
                {
                    if (!CrossPlatformInputManager.ButtonExists(powerButton.GetButtonName()))
                    {
                        button = new CrossPlatformInputManager.VirtualButton(powerButton.GetButtonName());
                        CrossPlatformInputManager.RegisterVirtualButton(button);
                    }
                }
            }

            // Register button axis
            if (powerType == PowerType.Button)
            {
                if (powerButton.GetButtonToAxis() && powerButton.GetAxisName() != "")
                {
                    buttonAxisName = powerButton.GetAxisName();
                    if (!CrossPlatformInputManager.AxisExists(buttonAxisName))
                    {
                        buttonAxis = new CrossPlatformInputManager.VirtualAxis(buttonAxisName);
                        CrossPlatformInputManager.RegisterVirtualAxis(buttonAxis);
                    }
                    // Unregister doesn't work correctly / Get axis reference (necessary if button gets disbled and enabled again)
                    if (powerButton.GetAxisName() != "" && CrossPlatformInputManager.AxisExists(powerButton.GetAxisName()))
                    {
                        buttonAxis = CrossPlatformInputManager.VirtualAxisReference(powerButton.GetAxisName());
                    }
                }
            }
        }