Easiest way to pause your Unity game | TimeScale | Pause | Resume | Unity | @Unity3DSchool


PauseManager.cs
using UnityEngine;

public class PauseManager : MonoBehaviour
{
    bool isPaused = false;
    public GameObject PauseMenu;
    float timeScale;

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Escape))
        {
            if(isPaused) Resume();
            else Pause();
        }
    }

    void Pause()
    {
        isPaused = true;
        PauseMenu.SetActive(true);
        timeScale = Time.timeScale;
        Time.timeScale = 0.0f;
    }

    void Resume()
    {
        isPaused = false;
        PauseMenu.SetActive(false);
        Time.timeScale = timeScale;
    }
}

GameManager.cs
using System.Collections;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(DebugCoroutine());
    }

    void Update()
    {
        if (Time.timeScale == 0) return;
        Debug.Log("Update is running...");
    }

    void FixedUpdate()
    {
        Debug.Log("FixedUpdate is running...");
    }

    IEnumerator DebugCoroutine()
    {
        while(true)
        {
            yield return new WaitWhile(() => Time.timeScale == 0);
            yield return new WaitForEndOfFrame();
            Debug.Log("coroutine is running...");
        }
    }
}

Understanding Mathf functions - Lerp, MoveTowards, PingPong | Diff | Mathf | Unity | @Unity3DSchool


TestScript.cs
using UnityEngine;
using UnityEngine.UI;

public class TestScript : MonoBehaviour
{
    public Slider lerpSlider;
    public Slider moveTowardsSlider;
    public Slider pingPongSlider;

    void Update()
    {
        //Lerp
        lerpSlider.value = Mathf.Lerp(lerpSlider.value, lerpSlider.maxValue, 0.5f * Time.deltaTime);
        //MoveTowards
        moveTowardsSlider.value = Mathf.MoveTowards(moveTowardsSlider.value, moveTowardsSlider.maxValue, 10f * Time.deltaTime);
        //PingPong
        pingPongSlider.value = Mathf.PingPong(20 * Time.time, pingPongSlider.maxValue);
    }
}

Custom Event Node - Global Broadcasting | Script Graph | Visual Scripting | Unity | @Unity3DSchool

Custom Event Node | Script Graph | Visual Scripting | Unity Game Engine | @Unity3DSchool

Drag & Drop 2D | World-Space 2D Objects | C# | Unity Game Engine


DragDrop2D.cs
using UnityEngine;

public class DragDrop2D : MonoBehaviour
{
    Vector3 offset;
    Collider2D collider2d;
    public string destinationTag = "DropArea";

    void Awake()
    {
        collider2d = GetComponent<Collider2D>();
    }

    void OnMouseDown()
    {
        offset = transform.position - MouseWorldPosition();
    }

    void OnMouseDrag()
    {
        transform.position = MouseWorldPosition() + offset;
    }

    void OnMouseUp()
    {
        collider2d.enabled = false;
        var rayOrigin = Camera.main.transform.position;
        var rayDirection = MouseWorldPosition() - Camera.main.transform.position;
        RaycastHit2D hitInfo;
        if (hitInfo = Physics2D.Raycast(rayOrigin, rayDirection))
        {
            if (hitInfo.transform.tag == destinationTag)
            {
                transform.position = hitInfo.transform.position + new Vector3(0, 0, -0.01f);
            }
        }
        collider2d.enabled = true;
    }

    Vector3 MouseWorldPosition()
    {
        var mouseScreenPos = Input.mousePosition;
        mouseScreenPos.z = Camera.main.WorldToScreenPoint(transform.position).z;
        return Camera.main.ScreenToWorldPoint(mouseScreenPos);
    }
}

Launching Projectile | Drawing Trajectory | Projectile Motion | Line Renderer |C#| Unity Game Engine


ProjectileLauncher.cs
using UnityEngine;

public class ProjectileLauncher : MonoBehaviour
{
    public Transform launchPoint;
    public GameObject projectile;
    public float launchSpeed = 10f;

    [Header("****Trajectory Display****")]
    public LineRenderer lineRenderer;
    public int linePoints = 175;
    public float timeIntervalInPoints = 0.01f;

    void Update()
    {
        if(lineRenderer != null)
        {
            if(Input.GetMouseButton(1))
            {
                DrawTrajectory();
                lineRenderer.enabled = true;
            }
            else
                lineRenderer.enabled = false;
        }
        if (Input.GetMouseButtonDown(0))
        {
            var _projectile = Instantiate(projectile, launchPoint.position, launchPoint.rotation);
            _projectile.GetComponent<Rigidbody>().velocity = launchSpeed * launchPoint.up;
        }
    }

    void DrawTrajectory()
    {
        Vector3 origin = launchPoint.position;
        Vector3 startVelocity = launchSpeed * launchPoint.up;
        lineRenderer.positionCount = linePoints;
        float time = 0;
        for (int i = 0; i < linePoints; i++)
        {
            // s = u*t + 1/2*g*t*t
            var x = (startVelocity.x * time) + (Physics.gravity.x / 2 * time * time);
            var y = (startVelocity.y * time) + (Physics.gravity.y / 2 * time * time);
            Vector3 point = new Vector3(x, y, 0);
            lineRenderer.SetPosition(i, origin + point);
            time += timeIntervalInPoints;
        }
    }
}

Animation Events | Event Functions | Animator Events | C# | Unity Game Engine


AnimationEventsDemo.cs
using UnityEngine;

public class AnimationEventsDemo : MonoBehaviour
{
    //no parameter
    public void TriggerEvent()
    {
        Debug.Log("event triggered");
    }

    //float parameter
    public void ScaleDownEvent(float scale)
    {
        transform.localScale = new Vector3(scale, scale, scale);
    }

    //int parameter
    public void ScaleUpEvent(int scale)
    {
        transform.localScale = new Vector3(scale, scale, scale);
    }

    //string parameter
    public void PrintLogEvent(string str)
    {
        Debug.Log(str);
    }

    //Object parameter
    public void SpawnObjectEvent(Object gameObject)
    {
        if (gameObject != null)
            Instantiate(gameObject);
    }

    //multiple parameters(float,int,string,object)
    public void MultiParamEvent(AnimationEvent e)
    {
        Debug.Log(e.floatParameter + "," + e.intParameter + "," + e.stringParameter);
        if (e.objectReferenceParameter != null)
        {
            Instantiate(e.objectReferenceParameter);
        }
    }
}

Group Opacity Controller | Child Opacity Controller | 2D & 3D | C# | Unity Game Engine


GroupOpacityController.cs (using Update)
using UnityEngine;

[ExecuteAlways]
public class GroupOpacityController : MonoBehaviour
{
    [Range(0f, 1f)]
    public float opacity = 1f;  
    Renderer[] renderers;
    SpriteRenderer[] spriteRenderers;

    float _previousOpacity;

    void Start()
    {
        renderers = GetComponentsInChildren<Renderer>();
        spriteRenderers = GetComponentsInChildren<SpriteRenderer>();
        SetOpacity(opacity);
    }

    void Update()
    {
        if(opacity != _previousOpacity)
        {
            SetOpacity(opacity); 
            _previousOpacity = opacity;
        }
    }

    void SetOpacity(float opacity)
    {
        if (renderers != null)
        {
            foreach (Renderer renderer in renderers)
            {
                for (int i = 0; i < renderer.sharedMaterials.Length; i++)
                {
                    Color color= renderer.sharedMaterials[i].color;
                    color.a = opacity;
                    MaterialPropertyBlock matBlock = new MaterialPropertyBlock();
                    matBlock.SetColor("_Color", color);
                    renderer.SetPropertyBlock(matBlock, i);
                }
            }
        }

        if (spriteRenderers != null)
        {
            foreach (SpriteRenderer spriteRenderer in spriteRenderers)
            {
                Color color = spriteRenderer.color;
                color.a = opacity;
                spriteRenderer.color = color;
            }
        }
    }
}
GroupOpacityController.cs (using Property)
using UnityEngine;

[ExecuteAlways]
public class GroupOpacityController : MonoBehaviour
{
    [SerializeField, Range(0f, 1f)]
    float _opacity = 1f;
    public float Opacity
    {
        get { return _opacity; }
        set
        {
            _opacity = Mathf.Clamp01(value);
            SetOpacity(_opacity);
        }
    }    

    Renderer[] renderers;
    SpriteRenderer[] spriteRenderers;
	
#if UNITY_EDITOR
    void OnValidate()
    {
        SetOpacity(_opacity);
    }
#endif

    void Start()
    {
        renderers = GetComponentsInChildren<Renderer>();
        spriteRenderers = GetComponentsInChildren<SpriteRenderer>();
        SetOpacity(_opacity);
    }

    void SetOpacity(float opacity)
    {
        if (renderers != null)
        {
            foreach (Renderer renderer in renderers)
            {
                for (int i = 0; i < renderer.sharedMaterials.Length; i++)
                {
                    Color color= renderer.sharedMaterials[i].color;
                    color.a = opacity;
                    MaterialPropertyBlock matBlock = new MaterialPropertyBlock();
                    matBlock.SetColor("_Color", color);
                    renderer.SetPropertyBlock(matBlock, i);
                }
            }
        }

        if (spriteRenderers != null)
        {
            foreach (SpriteRenderer spriteRenderer in spriteRenderers)
            {
                Color color = spriteRenderer.color;
                color.a = opacity;
                spriteRenderer.color = color;
            }
        }
    }
}

Input Cooldown | Input Delay | C# | Unity Game Engine


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

public class InputCooldown : MonoBehaviour
{
    public float cooldownTime = 0f;
    private bool isCooldown = false;

    private void Update()
    {
        if (Input.GetMouseButton(0) && !isCooldown)
        {
            StartCoroutine(Cooldown());
            SpawnSphere();
        }
    }

    private IEnumerator Cooldown()
    {
        isCooldown = true;
        yield return new WaitForSeconds(cooldownTime);
        isCooldown = false;
    }

    private void SpawnSphere()
    {
        GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
        sphere.transform.position = Camera.main.ScreenToWorldPoint(mousePos);
        sphere.AddComponent<Rigidbody>();
        GameObject.Destroy(sphere, 5);
    }
}

Simple Pickup and Inventory System | Pickup | Inventory | C# | Unity Game Engine


Item.cs
[System.Serializable]
public class Item
{
    public string name;
    public int count;

    public Item(string itemName, int itemCount)
    {
        name = itemName;
        count = itemCount;
    }
}

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

public class Inventory : MonoBehaviour
{
    public static Inventory instance;
    public List<Item> items = new List<Item>();

    void Awake()
    {
        if (instance != null)
            Destroy(gameObject);
        else
            instance = this;
    }

    public void AddItem(Item itemToAdd)
    {
        bool itemExists = false;

        foreach (Item item in items)
        {
            if(item.name == itemToAdd.name)
            {
                item.count += itemToAdd.count;
                itemExists = true;
                break;
            }
        }
        if(!itemExists)
        {
            items.Add(itemToAdd);
        }
        Debug.Log(itemToAdd.count + " " + itemToAdd.name + "added to inventory.");
    }

    public void RemoveItem(Item itemToRemove)
    {
        foreach (var item in items)
        {
            if(item.name == itemToRemove.name)
            {
                item.count -= itemToRemove.count;
                if(item.count <= 0)
                {
                    items.Remove(itemToRemove);
                }
                break;
            }
        }
        Debug.Log(itemToRemove.count + " " + itemToRemove.name + "removed from inventory.");
    }
}


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

public class Pickup : MonoBehaviour
{
    public Item item = new Item("Item Name", 1);

    void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Player"))
        {
            Inventory.instance.AddItem(item);
            Destroy(gameObject);
        }
    }
}

Print message in Console Log using Script Graph | Debug Log | Visual Scripting | Unity Game Engine


Lifecycle events and their execution order in a script graph | Visual Scripting | Unity Game Engine


Decorate console log messages | Debug.Log | C# | Unity Game Engine


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

public class MouseClickCounter : MonoBehaviour
{
    int clickCount = 0;

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Debug.Log($"<i>click</i> <b>count</b> <size=20>=</size> <color=cyan>{++clickCount}</color>");
        }
    }
}