Display Dialog | Popup Message with Options | C# | Unity Game Engine


PlayDisplayDialog.cs
using UnityEditor;

public class PlayDisplayDialog
{
    [MenuItem("Custom Menu/Play")]
    public static void Play()
    {
        bool playOutput = EditorUtility.DisplayDialog("Play", "Are you sure you want to enter play mode?", "Yes", "No");
        if (playOutput)
            EditorApplication.EnterPlaymode();
        else
            EditorUtility.DisplayDialog("Canceled", "You canceled the play mode.", "OK");
    }
}

Create Your Own Editor Window | Editor Scripting | C# | Unity Game Engine


TestWindow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class TestWindow : EditorWindow
{
    string myString = "Hi";
    float myFloat = 0f;
    bool myBool = false;
    bool isGroupEnabled = false;

    [MenuItem("Custom Window/Test Window")]
    public static void OpenWindow()
    {
        EditorWindow.GetWindow(typeof(TestWindow));
    }

    void OnGUI()
    {
        GUILayout.Label("Header", EditorStyles.boldLabel);
        myString = EditorGUILayout.TextField("Text", myString);

        isGroupEnabled = EditorGUILayout.BeginToggleGroup("Toggle Settings", isGroupEnabled);
        myFloat = EditorGUILayout.Slider("Slider", myFloat, -10, 10);
        myBool = EditorGUILayout.Toggle("Toggle", myBool);
        EditorGUILayout.EndToggleGroup();

        if(GUILayout.Button("Reset"))
        {
            myString = "Hi";
            myFloat = 0f;
            myBool = false;
            isGroupEnabled = false;
        }
    }
}

Sorting an Array using "Insertion Sort" | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] numbers = { 78, 55, 45, 98, 13 };

    void Start()
    {
        InsertionSort(numbers);
        Debug.Log("Sorted numbers : " + string.Join(',', numbers));
    }

    public void InsertionSort(int[] nums)
    {
        for (int i = 1; i < nums.Length; i++)
        {
            int temp = nums[i];
            int j;
            for (j = i - 1; j >= 0 && nums[j] > temp; j--)
            {
                nums[j + 1] = nums[j];
            }
            nums[j + 1] = temp;
        }
    }
}

Menu Items - Component Context | Editor Scripting | C# | Unity Game Engine


MenuItems_ComponentContext_Editor.cs
using UnityEngine;
using UnityEditor;

public class MenuItems_ComponentContext_Editor
{
    [MenuItem("CONTEXT/Camera/Set Orthographic")]
    public static void SetOrthographic()
    {
        Camera cam = Selection.activeGameObject.GetComponent<Camera>();
        cam.orthographic = true;
    }

    [MenuItem("CONTEXT/Camera/Set Perspective")]
    public static void SetPerspective(MenuCommand cmd)
    {
        Camera cam = cmd.context as Camera;
        cam.orthographic = false;
    }
}

Sorting an Array using "Bubble Sort" | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] numbers = { 78, 55, 45, 98, 13 };

    void Start()
    {
        BubbleSort(numbers);
        Debug.Log("Sorted numbers : " + string.Join(',', numbers));
    }

    public void BubbleSort(int[] nums)
    {
        for (int i = nums.Length - 2; i >= 0; i--)
        {
            for (int j = 0; j <= i; j++)
            {
                if (nums[j] > nums[j + 1])
                {
                    int temp = nums[j + 1];
                    nums[j + 1] = nums[j];
                    nums[j] = temp;
                }
            }
        }
    }
}

Menu Items - Conditional | Editor Scripting | C# | Unity Game Engine


MenuItems_Conditional_Editor.cs
using UnityEngine;
using UnityEditor;
public class MenuItems_Conditional_Editor
{
    [MenuItem("Conditional Menu/Process Material")]
    public static void DoSomethingWithMaterial()
    { }

    //Use the same name in MenuItem and pass 'true' to the second argument to mark the method as Validator.
    //The return type of method is bool and bool value depends on the type of selected object.
    //The menu item will be enabled when the selected object is a material otherwise disabled.
    [MenuItem("Conditional Menu/Process Material", true)]
    public static bool ProcessMaterialValidation()
    {
        return Selection.activeObject.GetType() == typeof(Material);
    }
}

Sorting an Array using "Selection Sort" | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] numbers = { 78, 55, 45, 98, 13 };

    void Start()
    {
        SelectionSort(numbers);
        Debug.Log("Sorted numbers : "+string.Join(",",numbers));
    }

    public void SelectionSort(int[] nums)
    {
        for (int i = 0; i < nums.Length - 1; i++)
        {
            int smallestNumIndex = i;
            for (int j = i + 1; j < nums.Length; j++)
            {
                if(nums[j]<nums[smallestNumIndex])
                    smallestNumIndex = j;
            }
            if(smallestNumIndex != i)
            {
                int temp = nums[i];
                nums[i] = nums[smallestNumIndex];
                nums[smallestNumIndex] = temp;
            }
        }
    }
}

Menu Items - Priority | Editor Scripting | C# | Unity Game Engine


MenuItems_Priority_Editor.cs
using UnityEngine;
using UnityEditor;

public class MenuItems_Priority_Editor
{
    [MenuItem("Priority Menu/Option 1", priority = 1)]
    public static void Option1Action()
    { }

    [MenuItem("Priority Menu/Option 2", priority = 101)]
    public static void Option2Action()
    { }

    [MenuItem("Priority Menu/Option 3", priority = 51)]
    public static void Option3Action()
    { }

    [MenuItem("Priority Menu/Option 4", priority = 2)]
    public static void Option4Action()
    { }
}

"Integer to Roman" Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int number = 1;

    void Start()
    {
        Debug.Log("Roman => "+IntToRoman(number));
    }

    public string IntToRoman(int num)
    {
        var lookup = new Dictionary<int, string>
        {
            {1000, "M"},{900, "CM"},{500, "D"},{400, "CD"},{100, "C"},{90, "XC"},
            {50, "L"},{40, "XL"},{10, "X"},{9, "IX"},{5, "V"},{4, "IV"},{1, "I"}
        };

        string result = "";
        foreach (var pair in lookup)
        {
            if (num <= 0)
                break;
            int quotient = num / pair.Key;
            for (int j = 0; j < quotient; j++)
            {
                num -= pair.Key;
                result += pair.Value;
            }
        }
        return result;
    }
}

Menu Items - Hotkeys | Editor Scripting | C# | Unity Game Engine


MenuItems_Hotkeys_Editor.cs
using UnityEngine;
using UnityEditor;

public class MenuItems_Hotkeys_Editor
{
    //Hotkey Shift-Ctrl-Alt A
    [MenuItem("Hotkeys Menu/Create Cube #%&a")]
    public static void CreateCube()
    {
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    }

    //Hotkey A
    [MenuItem("Hotkeys Menu/Option 2 _a")]
    public static void Option2Action()
    { }

    //Hotkey Left
    [MenuItem("Hotkeys Menu/Option 3 _Left")]
    public static void Option3Action()
    { }

    //Hotkey F1
    [MenuItem("Hotkeys Menu/Option 4 _F1")]
    public static void Option4Action()
    { }

    //Hotkey Home
    [MenuItem("Hotkeys Menu/Option 5 _Home")]
    public static void Option5Action()
    { }
}

''Container With Most Water" Problem and it's Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class Solution : MonoBehaviour
{
    public int[] heightArray = { 1, 8, 6, 2, 5, 4, 8, 3, 7 };

    void Start()
    {
        Debug.Log(MaxArea(heightArray));
    }

    public int MaxArea(int[] height)
    {
        int leftIndex = 0;
        int rightIndex = height.Length - 1;
        int maxArea = 0;

        while(leftIndex < rightIndex)
        {
            int area = Math.Min(height[leftIndex], height[rightIndex]) * (rightIndex - leftIndex);
            maxArea = Math.Max(maxArea, area);
            if (height[leftIndex] < height[rightIndex])
                ++leftIndex;
            else if (height[rightIndex] < height[leftIndex])
                --rightIndex;
            else
            {
                ++leftIndex;
                --rightIndex;
            }
        }

        return maxArea;
    }
}

Creating Menu Items | Editor Scripting | C# | Unity Game Engine


MenuItems_Editor.cs
using UnityEngine;
using UnityEditor;

public class MenuItems_Editor
{
    [MenuItem("Control Menu/Play")]
    public static void Play()
    {
        EditorApplication.EnterPlaymode();
    }

    [MenuItem("Control Menu/Stop")]
    public static void Stop()
    {
        EditorApplication.ExitPlaymode();
    }

    [MenuItem("Assets/Custom/Clear PlayerPrefs")]
    public static void DeleteAllPlayerPrefs()
    {
        PlayerPrefs.DeleteAll();
        EditorUtility.DisplayDialog("Cleared", "PlayerPrefs Cleared", "OK");
    }

    [MenuItem("Assets/Create/Cube at Center")]
    public static void CreateCenterCube()
    {
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        cube.transform.position = Vector3.zero;
    }
}

"Valid Parentheses" Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string input = "()";

    void Start()
    {
        Debug.Log(IsValid(input));
    }

    public bool IsValid(string s)
    {
        var valid_pairs = new Dictionary<char, char> { { '(', ')' }, { '{', '}' }, { '[', ']' } };
        var openingBrackets = new Stack<char>();
        foreach (var _char in s)
        {
            if(valid_pairs.ContainsKey(_char))
            {
                openingBrackets.Push(_char);
            }
            else
            {
                if(openingBrackets.Count == 0 || _char != valid_pairs[openingBrackets.Peek()])
                    return false;
                openingBrackets.Pop();
            }
        }
        return openingBrackets.Count == 0;
    }
}

Finding "Longest Common Prefix" string amongst an array of strings | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string[] strings = { "flower", "flow", "flight" };

    void Start()
    {
        Debug.Log("LCF => "+LongestCommonPrefix(strings));
    }

    public string LongestCommonPrefix(string[] strs)
    {
        if (strs == null || strs.Length == 0)
            return "";

        string prefix = strs[0];
        for (int i = 1; i < strs.Length; i++)
        {
            while(strs[i].IndexOf(prefix) != 0)
            {
                prefix = prefix.Substring(0, prefix.Length - 1);
                if (string.IsNullOrEmpty(prefix))
                    return "";
            }
        }
        return prefix;
    }
}

Adding Button in Custom Inspector | Editor Scripting | C# | Unity Game Engine


PlayerScript.cs
using UnityEngine;

public class PlayerScript : MonoBehaviour
{
    public int health = 100;
    public int maxHealth = 100;
}

PlayerScriptEditor.cs
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(PlayerScript))]
public class PlayerScriptEditor : Editor
{
    public override void OnInspectorGUI()
    {
        PlayerScript playerScript = (PlayerScript)target;
        playerScript.health = EditorGUILayout.IntField("Health", playerScript.health);
        playerScript.maxHealth = EditorGUILayout.IntField("Max-Health", playerScript.maxHealth);

        if(GUILayout.Button("Reset Values"))
        {
            playerScript.health = 100;
            playerScript.maxHealth = 100;
        }
    }
}

'Roman to Integer' Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string s = "III";

    void Start()
    {
        Debug.Log(s + " => " + RomanToInt(s));
    }

    public int RomanToInt(string s)
    {
        var map = new Dictionary<char, int> { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } };
        int num = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (i == 0 || map[s[i]] <= map[s[i - 1]])
            {
                num += map[s[i]];
            }
            else
            {
                num += map[s[i]] - 2 * map[s[i - 1]];
            }
        }
        return num;
    }
}

Use of "HelpBox" in Custom Inspector | Editor Scripting | C# | Unity Game Engine


PlayerScript.cs
using UnityEngine;

public class PlayerScript : MonoBehaviour
{
    public int health = 100;
    public int maxHealth = 100;
}

PlayerScriptEditor.cs
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(PlayerScript))]
public class PlayerScriptEditor : Editor
{
    public override void OnInspectorGUI()
    {
        PlayerScript playerScript = (PlayerScript)target;
        playerScript.health = EditorGUILayout.IntField("Health", playerScript.health);
        playerScript.maxHealth = EditorGUILayout.IntField("Max-Health", playerScript.maxHealth);

        if (playerScript.maxHealth > 0)
        {
            if(playerScript.maxHealth < playerScript.health)
                EditorGUILayout.HelpBox("Max Health is smaller than Health", MessageType.Warning);
        }
        else
        {
            EditorGUILayout.HelpBox("Max Health should be greater than 0", MessageType.Error);
        }
    }
}

'Two Sum' Problem and its Optimized Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] nums = { 2, 7, 11, 15 };
    public int target = 9;

    void Start()
    {
        var result = TwoSum(nums, target);
        Debug.Log("Result => " + string.Join(',', result));
    }

    public int[] TwoSum(int[] nums, int target)
    {
        var lookup = new Dictionary<int, int>();
        for (int i = 0; i < nums.Length; i++)
        {
            int secondNum = target - nums[i];
            if(lookup.ContainsKey(secondNum))
                return new[] {lookup[secondNum], i};
            lookup[nums[i]] = i;
        }
        return System.Array.Empty<int>();
    }
}

Use of "DrawDefaultInspector" method in Custom Inspector | Editor Scripting | C# | Unity Game Engine


PlayerScript.cs
using UnityEngine;

public class PlayerScript : MonoBehaviour
{
    public int health = 100;
    public int maxHealth = 100;
}

PlayerScriptEditor.cs
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(PlayerScript))]
public class PlayerScriptEditor : Editor
{
    public override void OnInspectorGUI()
    {
        PlayerScript playerScript = (PlayerScript)target;
        DrawDefaultInspector();

        if (playerScript.maxHealth > 0)
            EditorGUILayout.LabelField("Health %", playerScript.health * 100 / playerScript.maxHealth + "%");
    }
}

Check if number is 'Palindrome Number' | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int x = 121;

    void Start()
    {
        Debug.Log(IsPalindrome(x));
    }

    public bool IsPalindrome(int x)
    {
        if(x<0 || (x%10==0 && x!=0))
            return false;

        int reversedNum = 0;
        while(x > reversedNum)
        {
            reversedNum = reversedNum * 10 + (x % 10);
            x /= 10;
        }

        return x == reversedNum || x == reversedNum / 10;
    }
}

Building a Custom Inspector | Editor Scripting | C# | Unity Game Engine


PlayerScript.cs
using UnityEngine;

public class PlayerScript : MonoBehaviour
{
    public int health = 100;
    public int maxHealth = 100;
}

PlayerScriptEditor.cs
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(PlayerScript))]
public class PlayerScriptEditor : Editor
{
    public override void OnInspectorGUI()
    {
        PlayerScript playerScript = (PlayerScript)target;
        playerScript.health = EditorGUILayout.IntField("Health", playerScript.health);
        playerScript.maxHealth = EditorGUILayout.IntField("Max-Health", playerScript.maxHealth);

        EditorGUILayout.Space();
        EditorGUILayout.BeginHorizontal("box");
        if (playerScript.maxHealth > 0)
        {
            EditorGUILayout.LabelField("Health %", playerScript.health * 100 / playerScript.maxHealth + "%");
        }
        EditorGUILayout.EndHorizontal();
    }
}

Two Sum Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public int[] nums = { 2, 7, 11, 15 };
    public int target = 9;

    private void Start()
    {
        var result = TwoSum(nums, target);
        Debug.Log("Result => "+string.Join(',',result));
    }

    public int[] TwoSum(int[] nums, int target)
    {
        for (int i = 0; i < nums.Length-1; i++)
        {
            for (int j = i + 1; j < nums.Length; j++)
            {
                int sum = nums[i] + nums[j];
                if(sum == target)
                    return new int[]{i, j};
            }
        }
        return new int[] { -1, -1 };
    }
}