├── .gitattributes
├── .DS_Store
├── Addendum
├── SimpleSample.uxml
├── .DS_Store
├── B22128_05.unitypackage
├── myButton.uss
├── B22128_01.unitypackage
├── B22128_02.unitypackage
├── B22128_03.unitypackage
├── B22128_04.unitypackage
├── B22128_06.unitypackage
├── B22128_07.unitypackage
├── buttonStyle.uss
├── SceneLoader.cs
├── UIToolkitExample02.cs
├── UIToolkitExample.cs
├── UIToolkitExample03.cs
├── BurstExample.cs
├── JobExample.cs
├── UIToolkitExample04.cs
└── PlayerController04.cs
├── Chapter01
├── .DS_Store
└── VariablesExample.cs
├── Chapter03
├── .DS_Store
└── DelegateExample.cs
├── Chapter04
├── .DS_Store
├── Player01.cs
├── GameController.cs
├── Mover.cs
├── Enemy01.cs
├── Rotator.cs
├── PlayerController01.cs
├── PlayerMovement01.cs
├── GameManager01.cs
├── Health.cs
├── ExampleScript.cs
├── Player02.cs
└── AudioManager.cs
├── Chapter05
├── .DS_Store
├── SceneLoader.cs
├── EnemyAI.cs
├── Inventory01.cs
├── ApplyForce.cs
├── EnemyController01.cs
├── GameManager02.cs
├── LaunchProjectile.cs
├── MyNetworkManager.cs
├── DayNightCycle.cs
├── PlayerMovement02.cs
├── PlayerJump.cs
└── TerrainDeformer.cs
├── Chapter06
├── .DS_Store
├── Inventory02.cs
├── Inventoryv2.cs
├── PowerUpManager.cs
├── ListExample02.cs
├── InventoryManager01.cs
├── InventoryManager02.cs
├── ArrayExample.cs
├── ListExample01.cs
└── Point2DExample.cs
├── Chapter07
├── .DS_Store
├── RotateSymbol.cs
├── MainMenu.cs
├── PlayerMovement03.cs
├── PlayerController.cs
├── CombatController.cs
├── PlayerController02.cs
├── NarrativeController.cs
└── SettingsMenu.cs
├── Chapter08
├── .DS_Store
├── PlayerController03.cs
├── GravityAndImpulseDemo.cs
├── InteractiveDoor.cs
├── CharacterPhysicsReactions.cs
├── ForceAndTorqueDemo.cs
└── BridgeCollapse.cs
├── Chapter09
├── .DS_Store
├── InventoryManager.cs
├── ObjectPool.cs
├── InvokeSendMessageCoroutineExample.cs
└── PreferencesManager.cs
├── Chapter10
├── .DS_Store
├── RescueRobot.cs
├── SimpleNavAgent.cs
├── UrbanCrowdMovement.cs
├── WildlifeBehavior.cs
├── EnemyController02.cs
├── EnemyPatrol.cs
├── UtilityDecider.cs
├── BattlefieldNavigation.cs
├── HideAndSeekAI.cs
├── NPCAgent.cs
├── PatrolGuardAI.cs
└── EnemyController03.cs
├── Chapter11
├── .DS_Store
├── PlayerScore.cs
└── GameActions.cs
├── Chapter12
├── .DS_Store
└── FrameRateCounter.cs
├── Chapter13
├── .DS_Store
├── Collectibles.cs
├── UIManager01.cs
├── Enemy02.cs
└── PlayerMovement.cs
├── Chapter14
├── .DS_Store
├── GrabObject.cs
├── ARSetup.cs
├── AssetBundleLoader.cs
├── ARSceneSetup.cs
├── VRSetup.cs
└── ARInteraction.cs
├── Chapter15
├── .DS_Store
├── MotionControl.cs
├── UIManager02.cs
├── CenteredUI.cs
├── ResponsivePanel.cs
├── VerticalList.cs
├── SwipeControl.cs
└── ResponsiveButton.cs
├── .idea
└── .idea.B22128_Chapter_CodeSamples.dir
│ └── .idea
│ ├── encodings.xml
│ ├── vcs.xml
│ ├── indexLayout.xml
│ ├── .gitignore
│ └── cody_history.xml
├── LICENSE
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.unitypackage filter=lfs diff=lfs merge=lfs -text
2 |
--------------------------------------------------------------------------------
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/.DS_Store
--------------------------------------------------------------------------------
/Addendum/SimpleSample.uxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/Addendum/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Addendum/.DS_Store
--------------------------------------------------------------------------------
/Chapter01/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter01/.DS_Store
--------------------------------------------------------------------------------
/Chapter03/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter03/.DS_Store
--------------------------------------------------------------------------------
/Chapter04/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter04/.DS_Store
--------------------------------------------------------------------------------
/Chapter05/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter05/.DS_Store
--------------------------------------------------------------------------------
/Chapter06/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter06/.DS_Store
--------------------------------------------------------------------------------
/Chapter07/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter07/.DS_Store
--------------------------------------------------------------------------------
/Chapter08/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter08/.DS_Store
--------------------------------------------------------------------------------
/Chapter09/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter09/.DS_Store
--------------------------------------------------------------------------------
/Chapter10/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter10/.DS_Store
--------------------------------------------------------------------------------
/Chapter11/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter11/.DS_Store
--------------------------------------------------------------------------------
/Chapter12/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter12/.DS_Store
--------------------------------------------------------------------------------
/Chapter13/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter13/.DS_Store
--------------------------------------------------------------------------------
/Chapter14/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter14/.DS_Store
--------------------------------------------------------------------------------
/Chapter15/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Unity-6-Game-Development-with-C-Scripting/HEAD/Chapter15/.DS_Store
--------------------------------------------------------------------------------
/Addendum/B22128_05.unitypackage:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:a72e1f6200269c3e18abd8e763bd952e99845df7c99964618ff6dc2aa12eae34
3 | size 42070
4 |
--------------------------------------------------------------------------------
/Addendum/myButton.uss:
--------------------------------------------------------------------------------
1 | /* USS: Styling the Button */
2 |
3 | .myButton {
4 |
5 | width: 200px; height: 50px;
6 | background-color: #4CAF50; font-size: 18px;
7 | }
--------------------------------------------------------------------------------
/Addendum/B22128_01.unitypackage:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:96ca22258cc34359b9de36070be051190aa8cab4594ab9446c7813284032eedf
3 | size 3045412
4 |
--------------------------------------------------------------------------------
/Addendum/B22128_02.unitypackage:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:279e1a520bab2581a6d78c4da568ec0870e49d30a62c6c54349474562747b8be
3 | size 3047187
4 |
--------------------------------------------------------------------------------
/Addendum/B22128_03.unitypackage:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:69964e4e144c64eaa98d5043b644524d0b84d25603f7a4b63d2543226f00f13b
3 | size 36029137
4 |
--------------------------------------------------------------------------------
/Addendum/B22128_04.unitypackage:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:de5fcfd192184368a232f91b88c9847a3c2aeb2327e45aa22b95f4078e739c7d
3 | size 3051461
4 |
--------------------------------------------------------------------------------
/Addendum/B22128_06.unitypackage:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:a9c481c731456ac22d68dffc52ac4c35d301c37a126554102353c76d17c9846b
3 | size 974026
4 |
--------------------------------------------------------------------------------
/Addendum/B22128_07.unitypackage:
--------------------------------------------------------------------------------
1 | version https://git-lfs.github.com/spec/v1
2 | oid sha256:010b9cfd28400365ae95b5d2949c8fd0f97a491dc8b98b1355686a58fe01475f
3 | size 1537415
4 |
--------------------------------------------------------------------------------
/Addendum/buttonStyle.uss:
--------------------------------------------------------------------------------
1 | /* USS: Styling the button */
2 |
3 | .myButton {
4 |
5 | width: 150px; height: 40px;
6 | background-color: #3498db; color: white;
7 | font-size: 16px; border-radius: 5px;
8 | }
--------------------------------------------------------------------------------
/.idea/.idea.B22128_Chapter_CodeSamples.dir/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/.idea.B22128_Chapter_CodeSamples.dir/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Chapter05/SceneLoader.cs:
--------------------------------------------------------------------------------
1 | // SceneLoader.cs
2 | using UnityEngine;
3 | using UnityEngine.SceneManagement;
4 |
5 | public class SceneLoader : MonoBehaviour
6 | {
7 | public void LoadGameLevel()
8 | {
9 | SceneManager.LoadScene("GameLevel");
10 | }
11 | }
--------------------------------------------------------------------------------
/.idea/.idea.B22128_Chapter_CodeSamples.dir/.idea/indexLayout.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Addendum/SceneLoader.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using UnityEngine.SceneManagement;
3 | public class SceneLoader : MonoBehaviour
4 | {
5 | public void LoadNewScene(string sceneName)
6 | {
7 | // Asynchronously load the scene in the background
8 | SceneManager.LoadSceneAsync(sceneName);
9 | }
10 | }
--------------------------------------------------------------------------------
/Chapter05/EnemyAI.cs:
--------------------------------------------------------------------------------
1 | // EnemyAI.cs
2 | using UnityEngine;
3 | using UnityEngine.AI;
4 |
5 | public class EnemyAI : MonoBehaviour
6 | {
7 | public NavMeshAgent agent;
8 | public Transform player;
9 |
10 | void Update()
11 | {
12 | agent.SetDestination(player.position);
13 | }
14 | }
--------------------------------------------------------------------------------
/Chapter04/Player01.cs:
--------------------------------------------------------------------------------
1 | // Player01.cs
2 | using UnityEngine;
3 |
4 | public class Player01 : MonoBehaviour
5 | {
6 | public Health health; // Reference to the Health script
7 |
8 | void Start()
9 | {
10 | // Accessing methods from the Health script
11 | health.TakeDamage(10);
12 | }
13 | }
--------------------------------------------------------------------------------
/Chapter07/RotateSymbol.cs:
--------------------------------------------------------------------------------
1 | // RotateSymbol.cs
2 | using UnityEngine; // Inserted for completeness
3 | public class RotateSymbol : MonoBehaviour
4 | {
5 | public void Rotate(float angle)
6 | {
7 | transform.Rotate(0, 0, angle);
8 | }
9 | }
10 |
11 | // Note: In the book, this is a code snippet. It lacks the "Using UnityEngine" statement.
--------------------------------------------------------------------------------
/Chapter05/Inventory01.cs:
--------------------------------------------------------------------------------
1 | // Inventory01.cs
2 | using System.Collections.Generic;
3 | using UnityEditor;
4 | using UnityEngine;
5 |
6 | public class Inventory01 : MonoBehaviour
7 | {
8 | public List items = new List();
9 |
10 | public void AddItem(Progress.Item item)
11 | {
12 | items.Add(item);
13 | }
14 | }
--------------------------------------------------------------------------------
/Chapter13/Collectibles.cs:
--------------------------------------------------------------------------------
1 | // Collectibles.cs
2 | using UnityEngine;
3 |
4 | public class Collectibles : MonoBehaviour
5 | {
6 | void OnTriggerEnter2D(Collider2D other)
7 | {
8 | if (other.CompareTag("Player"))
9 | {
10 | // Logic for collecting the item
11 | Destroy(gameObject);
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/Chapter05/ApplyForce.cs:
--------------------------------------------------------------------------------
1 | // ApplyForce.cs
2 | using UnityEngine;
3 |
4 | public class ApplyForce : MonoBehaviour
5 | {
6 | public Rigidbody rb;
7 | public Vector3 forceDirection;
8 | public float forceMagnitude;
9 |
10 | void Start()
11 | {
12 | rb.AddForce(forceDirection.normalized *
13 | forceMagnitude);
14 | }
15 | }
--------------------------------------------------------------------------------
/Chapter05/EnemyController01.cs:
--------------------------------------------------------------------------------
1 | // EnemyController02.cs
2 | using UnityEngine;
3 | using UnityEngine.AI;
4 |
5 | public class EnemyController01 : MonoBehaviour
6 | {
7 | public NavMeshAgent agent;
8 | public Transform player;
9 |
10 | void Update()
11 | {
12 | // Follow the player
13 | agent.SetDestination(player.position);
14 | }
15 | }
--------------------------------------------------------------------------------
/Chapter04/GameController.cs:
--------------------------------------------------------------------------------
1 | // GameController.cs
2 | using UnityEngine;
3 |
4 | public class GameController : MonoBehaviour
5 | {
6 | void Start()
7 | {
8 | // Broadcast message to all components in the GameController
9 | // object and its children
10 | gameObject.BroadcastMessage("Initialize",
11 | SendMessageOptions.RequireReceiver);
12 | }
13 | }
--------------------------------------------------------------------------------
/Chapter15/MotionControl.cs:
--------------------------------------------------------------------------------
1 | // MotionControl.cs
2 | using UnityEngine;
3 |
4 | public class MotionControl : MonoBehaviour
5 | {
6 | public float sensitivity = 1.0f;
7 |
8 | void Update()
9 | {
10 | Vector3 tilt = Input.acceleration * sensitivity;
11 | // Use tilt.x and tilt.y to control game objects
12 | transform.Translate(tilt.x, 0, tilt.y);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/.idea/.idea.B22128_Chapter_CodeSamples.dir/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Rider ignored files
5 | /projectSettingsUpdater.xml
6 | /modules.xml
7 | /contentModel.xml
8 | /.idea.B22128_Chapter_CodeSamples.iml
9 | # Editor-based HTTP Client requests
10 | /httpRequests/
11 | # Datasource local storage ignored files
12 | /dataSources/
13 | /dataSources.local.xml
14 |
--------------------------------------------------------------------------------
/Chapter04/Mover.cs:
--------------------------------------------------------------------------------
1 | // Mover.cs
2 |
3 | using UnityEngine;
4 |
5 | public class Mover: MonoBehaviour
6 | {
7 | public float speed = 5.0f;
8 |
9 | void Update()
10 | {
11 | // Move the game object forward continuously at the
12 | // speed specified
13 | transform.Translate(Vector3.forward * speed *
14 | Time.deltaTime);
15 | }
16 | }
--------------------------------------------------------------------------------
/Chapter07/MainMenu.cs:
--------------------------------------------------------------------------------
1 | // MainMenu.cs
2 | using UnityEngine;
3 | using UnityEngine.SceneManagement;
4 |
5 | public class MainMenu : MonoBehaviour
6 | {
7 | public void StartGame()
8 | {
9 | // Load the game scene
10 | SceneManager.LoadScene("GameScene");
11 | }
12 |
13 | public void QuitGame()
14 | {
15 | // Exit the game
16 | Application.Quit();
17 | }
18 | }
--------------------------------------------------------------------------------
/Chapter04/Enemy01.cs:
--------------------------------------------------------------------------------
1 | // Enemy01.cs
2 | using UnityEngine;
3 |
4 | public class Enemy01 : MonoBehaviour
5 | {
6 | void OnCollisionEnter(Collision collision)
7 | {
8 | if (collision.gameObject.CompareTag("Player"))
9 | {
10 | // Send message to the collided player
11 | // object to take damage
12 | collision.gameObject.SendMessage("TakeDamage", 10);
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/Chapter04/Rotator.cs:
--------------------------------------------------------------------------------
1 | // Rotator.cs
2 |
3 | using UnityEngine;
4 |
5 | public class Rotator: MonoBehaviour
6 | {
7 | public float rotationSpeed = 90.0f;
8 | // Degrees per second
9 |
10 | void Update()
11 | {
12 | // Rotate the game object around its up axis at the
13 | // speed specified
14 | transform.Rotate(Vector3.up, rotationSpeed *
15 | Time.deltaTime);
16 | }
17 | }
--------------------------------------------------------------------------------
/Chapter04/PlayerController01.cs:
--------------------------------------------------------------------------------
1 | // PlayerController01.cs
2 |
3 | using UnityEngine;
4 |
5 | public class PlayerController01 : MonoBehaviour
6 | {
7 | public float speed = 5.0f;
8 |
9 | void Update()
10 | {
11 | float moveHorizontal = Input.GetAxis("Horizontal");
12 | Vector3 movement = new Vector3(moveHorizontal, 0.0f,
13 | 0.0f);
14 | transform.position += speed * Time.deltaTime * movement;
15 | }
16 | }
--------------------------------------------------------------------------------
/Chapter06/Inventory02.cs:
--------------------------------------------------------------------------------
1 | // Inventory01.cs
2 |
3 | using System.Collections.Generic;
4 | using UnityEditor;
5 | using UnityEngine;
6 |
7 | [CreateAssetMenu(fileName = "New Inventory", menuName = "Inventory System/Inventory")]
8 | public class Inventory02 : ScriptableObject
9 | {
10 | public List items = new List();
11 |
12 | public void AddItem(Progress.Item itemToAdd)
13 | {
14 | // Add item logic here
15 | }
16 | }
--------------------------------------------------------------------------------
/Chapter12/FrameRateCounter.cs:
--------------------------------------------------------------------------------
1 | // FrameRateCounter.cs
2 | using UnityEngine;
3 | using UnityEngine.UI;
4 |
5 | public class FrameRateCounter : MonoBehaviour
6 | {
7 | public Text frameRateText;
8 | private float deltaTime = 0.0f;
9 |
10 | void Update()
11 | {
12 | deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f;
13 | float fps = 1.0f / deltaTime;
14 | frameRateText.text = Mathf.Ceil(fps).ToString() + " FPS";
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Addendum/UIToolkitExample02.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine.UIElements;
2 |
3 | public class UIToolkitExample02 : MonoBehaviour
4 | {
5 | private void OnEnable()
6 | {
7 | // Get the root visual element from the current UI document
8 | var root = GetComponent().rootVisualElement;
9 |
10 | // Create a new Button
11 | Button myButton = new Button(); myButton.text = "Click Me!";
12 | // Add the button to the root element
13 | root.Add(myButton);
14 | }
15 | }
--------------------------------------------------------------------------------
/Chapter10/RescueRobot.cs:
--------------------------------------------------------------------------------
1 | // RescueRobot.cs
2 | using UnityEngine;
3 | using UnityEngine.AI;
4 |
5 | public class RescueRobot : MonoBehaviour
6 | {
7 | public Transform target;
8 |
9 | void Start()
10 | {
11 | NavMeshAgent agent = GetComponent();
12 | agent.SetDestination(target.position);
13 | }
14 |
15 | void Update()
16 | {
17 | // Add additional logic for dynamic obstacles and other rescue-specific behaviors
18 | }
19 | }
--------------------------------------------------------------------------------
/Chapter15/UIManager02.cs:
--------------------------------------------------------------------------------
1 | // UIManager02.cs
2 | using UnityEngine;
3 | using UnityEngine.UI;
4 |
5 | public class UIManager02 : MonoBehaviour
6 | {
7 | public CanvasScaler canvasScaler;
8 |
9 | void Start()
10 | {
11 | // Set the reference resolution to ensure consistent UI scaling
12 | canvasScaler.referenceResolution = new Vector2(1920, 1080);
13 | canvasScaler.uiScaleMode =
14 | CanvasScaler.ScaleMode.ScaleWithScreenSize;
15 | }
16 | }
--------------------------------------------------------------------------------
/Chapter07/PlayerMovement03.cs:
--------------------------------------------------------------------------------
1 | // PlayerMovement01.cs
2 | using UnityEngine;
3 |
4 | public class PlayerMovement03 : MonoBehaviour
5 | {
6 | public float moveSpeed = 5f;
7 |
8 | void Update()
9 | {
10 | float moveX = Input.GetAxis("Horizontal") *
11 | moveSpeed * Time.deltaTime;
12 | float moveZ = Input.GetAxis("Vertical") *
13 | moveSpeed * Time.deltaTime;
14 |
15 | transform.Translate(moveX, 0f, moveZ);
16 | }
17 | }
--------------------------------------------------------------------------------
/Chapter10/SimpleNavAgent.cs:
--------------------------------------------------------------------------------
1 | // SimpleNavAgent.cs
2 | using UnityEngine;
3 | using UnityEngine.AI;
4 |
5 | public class SimpleNavAgent : MonoBehaviour
6 | {
7 | public Transform target; // Drag your target in the Inspector
8 | private NavMeshAgent agent;
9 |
10 | void Start()
11 | {
12 | agent = GetComponent();
13 | }
14 |
15 | void Update()
16 | {
17 | if(target != null)
18 | agent.SetDestination(target.position);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Chapter07/PlayerController.cs:
--------------------------------------------------------------------------------
1 | // PlayerController03.cs
2 | using UnityEngine;
3 |
4 | public class PlayerController : MonoBehaviour
5 | {
6 | public float speed = 5.0f;
7 |
8 | void Update()
9 | {
10 | float moveHorizontal = Input.GetAxis("Horizontal");
11 | float moveVertical = Input.GetAxis("Vertical");
12 |
13 | Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
14 |
15 | transform.Translate(movement * speed * Time.deltaTime);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Chapter14/GrabObject.cs:
--------------------------------------------------------------------------------
1 | // GrabObject.cs
2 |
3 | //Needs XR Interaction Toolkit package installed
4 |
5 | /*
6 | using UnityEngine;
7 | using UnityEngine.XR.Interaction.Toolkit;
8 |
9 | public class GrabObject : MonoBehaviour
10 | {
11 | public XRBaseInteractable interactable;
12 |
13 | void Start()
14 | {
15 | interactable.onSelectEnter.AddListener(OnGrab);
16 | }
17 |
18 | void OnGrab(XRBaseInteractor interactor)
19 | {
20 | Debug.Log("Object grabbed");
21 | }
22 | } */
--------------------------------------------------------------------------------
/Chapter15/CenteredUI.cs:
--------------------------------------------------------------------------------
1 | // CenteredUI.cs
2 | using UnityEngine;
3 | using UnityEngine.UI;
4 |
5 | public class CenteredUI : MonoBehaviour
6 | {
7 | public RectTransform uiElement;
8 |
9 | void Start()
10 | {
11 | // Set the anchor points to the center
12 | uiElement.anchorMin = new Vector2(0.5f, 0.5f);
13 | uiElement.anchorMax = new Vector2(0.5f, 0.5f);
14 | uiElement.pivot = new Vector2(0.5f, 0.5f);
15 | uiElement.anchoredPosition = Vector2.zero;
16 | }
17 | }
--------------------------------------------------------------------------------
/Chapter04/PlayerMovement01.cs:
--------------------------------------------------------------------------------
1 | // PlayerMovement01.cs
2 |
3 | using UnityEngine;
4 |
5 | public class PlayerMovement01 : MonoBehaviour
6 | {
7 | public float speed = 5.0f;
8 |
9 | void Update()
10 | {
11 | float horizontal = Input.GetAxis("Horizontal") *
12 | speed * Time.deltaTime;
13 | float vertical = Input.GetAxis("Vertical") * speed *
14 | Time.deltaTime;
15 |
16 | transform.Translate(horizontal, 0f, vertical);
17 | }
18 | }
--------------------------------------------------------------------------------
/Chapter05/GameManager02.cs:
--------------------------------------------------------------------------------
1 | // GameManager01.cs
2 | using UnityEngine;
3 |
4 | public class GameManager02 : MonoBehaviour
5 | {
6 | public static GameManager02 Instance;
7 |
8 | void Awake()
9 | {
10 | if (Instance == null)
11 | {
12 | Instance = this;
13 | DontDestroyOnLoad(gameObject);
14 | }
15 | else if (Instance != this)
16 | {
17 | Destroy(gameObject);
18 | }
19 | }
20 |
21 | // Your game state data and methods here
22 | }
--------------------------------------------------------------------------------
/Chapter07/CombatController.cs:
--------------------------------------------------------------------------------
1 | // CombatController.cs
2 | using UnityEngine; // Inserted for completeness
3 | public class CombatController : MonoBehaviour
4 | {
5 | private int comboSequence = 0;
6 |
7 | public void Attack()
8 | {
9 | comboSequence++;
10 | if (comboSequence == 3)
11 | {
12 | // Perform special attack
13 | comboSequence = 0;
14 | }
15 | }
16 | }
17 |
18 | // Note: In the book, this is a code snippet. It lacks the "Using UnityEngine" statement.
--------------------------------------------------------------------------------
/Chapter11/PlayerScore.cs:
--------------------------------------------------------------------------------
1 | // PlayerScore.cs
2 |
3 | // Needs NetCode package installed
4 | /*
5 | using Unity.Netcode;
6 | using UnityEngine;
7 |
8 | public class PlayerScore : NetworkBehaviour {
9 | public NetworkVariable score =
10 | new NetworkVariable(0, NetworkVariableReadPermission.Everyone,
11 | NetworkVariableWritePermission.Server);
12 |
13 | [ServerRpc]
14 | public void AddScore(int points) {
15 | score.Value += points;
16 | }
17 | }
18 | */
--------------------------------------------------------------------------------
/Chapter05/LaunchProjectile.cs:
--------------------------------------------------------------------------------
1 | // LaunchProjectile.cs
2 | using UnityEngine;
3 |
4 | public class LaunchProjectile : MonoBehaviour
5 | {
6 | public Rigidbody2D projectile;
7 | public float launchAngle = 45f;
8 | public float launchForce = 10f;
9 |
10 | void Start()
11 | {
12 | Vector2 launchDirection = Quaternion.Euler(0, 0, launchAngle)
13 | * Vector2.right;
14 | projectile.AddForce(launchDirection * launchForce,
15 | ForceMode2D.Impulse);
16 | }
17 | }
--------------------------------------------------------------------------------
/Chapter08/PlayerController03.cs:
--------------------------------------------------------------------------------
1 | // PlayerController03.cs
2 | using UnityEngine;
3 |
4 | public class PlayerController03 : MonoBehaviour
5 | {
6 | Animator animator;
7 |
8 | void Start()
9 | {
10 | animator = GetComponent();
11 | }
12 |
13 | void Update()
14 | {
15 | if (Input.GetKeyDown(KeyCode.Space))
16 | {
17 | // Set the 'isJumping' parameter to true when the space bar is pressed
18 | animator.SetBool("isJumping", true);
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/Chapter13/UIManager01.cs:
--------------------------------------------------------------------------------
1 | // UIManager01.cs
2 | using UnityEngine;
3 | using UnityEngine.UI;
4 |
5 | public class UIManager01 : MonoBehaviour
6 | {
7 | public Text scoreText;
8 | private int score = 0;
9 |
10 | void Start()
11 | {
12 | UpdateScoreText();
13 | }
14 |
15 | public void IncrementScore(int amount)
16 | {
17 | score += amount;
18 | UpdateScoreText();
19 | }
20 |
21 | void UpdateScoreText()
22 | {
23 | scoreText.text = "Score: " + score.ToString();
24 | }
25 | }
--------------------------------------------------------------------------------
/Chapter07/PlayerController02.cs:
--------------------------------------------------------------------------------
1 | // PlayerController03.cs (version 2)
2 | using UnityEngine;
3 |
4 | public class PlayerController02 : MonoBehaviour
5 | {
6 | void Update()
7 | { // Left Arrow moves Player to the left
8 | if (Input.GetKeyDown(KeyCode.LeftArrow))
9 | {
10 | transform.Translate(-1, 0, 0);
11 | } // Right Arrow moves Player to the right
12 | else if (Input.GetKeyDown(KeyCode.RightArrow))
13 | {
14 | transform.Translate(1, 0, 0);
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/Addendum/UIToolkitExample.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine.UIElements;
2 |
3 | public class UIToolkitExample : MonoBehaviour
4 | {
5 | private void OnEnable()
6 | {
7 | // Get the root visual element from the current UI document var root = GetComponent().rootVisualElement;
8 |
9 | // Create a new button
10 | Button myButton = new Button(); myButton.text = "Click Me!";
11 |
12 | // Register a click event
13 | myButton.clicked += () => Debug.Log("Button Clicked!");
14 |
15 | // Add the button to the root element root.Add(myButton);
16 | }
17 | }
--------------------------------------------------------------------------------
/Chapter06/Inventoryv2.cs:
--------------------------------------------------------------------------------
1 | // Inventory01.cs (version 2)
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | public class Inventory : MonoBehaviour
6 | {
7 | private List items = new List();
8 |
9 | public void AddItem(string item)
10 | {
11 | items.Add(item);
12 | }
13 |
14 | public bool RemoveItem(string item)
15 | {
16 | return items.Remove(item);
17 | }
18 |
19 | public bool CheckItem(string item)
20 | {
21 | return items.Contains(item);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Chapter06/PowerUpManager.cs:
--------------------------------------------------------------------------------
1 | // PowerUpManager.cs
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | public class PowerUpManager : MonoBehaviour
6 | {
7 | HashSet collectedPowerUps = new HashSet();
8 |
9 | void CollectPowerUp(string powerUpName)
10 | {
11 | // Adds the power-up to the collection if it's not already present
12 | bool added = collectedPowerUps.Add(powerUpName);
13 | if (added)
14 | {
15 | Debug.Log(powerUpName + " collected!");
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/Addendum/UIToolkitExample03.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using UnityEngine.UIElements;
3 |
4 | public class UIToolkitExample03 : MonoBehaviour
5 | {
6 | private void OnEnable()
7 | {
8 | var root = GetComponent().rootVisualElement;
9 |
10 | // Create a button
11 | Button myButton = new Button(); myButton.text = "Click Me!";
12 |
13 | // Register a click event handler
14 | myButton.clicked += () => Debug.Log("Button clicked!");
15 |
16 | // Add the button to the root element root.Add(myButton);
17 | root.Add(myButton);
18 | }
19 | }
--------------------------------------------------------------------------------
/Addendum/BurstExample.cs:
--------------------------------------------------------------------------------
1 | using Unity.Burst;
2 | using Unity.Jobs;
3 | using UnityEngine;
4 |
5 | // Needs Unity's Job and Burst system installed
6 | /* public class BurstExample : MonoBehaviour
7 | {
8 | [BurstCompile]
9 | struct ComplexCalculationJob : IJob
10 | {
11 | public void Execute()
12 | {
13 | // Perform complex calculations here
14 | }
15 | }
16 | void Start()
17 | {
18 | ComplexCalculationJob job = new ComplexCalculationJob();
19 | JobHandle jobHandle = job.Schedule();
20 | jobHandle.Complete(); // Ensures the job completes before proceeding
21 | }
22 | } */
--------------------------------------------------------------------------------
/Chapter07/NarrativeController.cs:
--------------------------------------------------------------------------------
1 | // NarrativeController.cs
2 | using UnityEngine; // Inserted for completeness
3 | public class NarrativeController : MonoBehaviour
4 | {
5 | public void MakeChoice(int choice)
6 | {
7 | switch (choice)
8 | {
9 | case 1:
10 | // Trigger one storyline
11 | break;
12 | case 2:
13 | // Trigger an alternative storyline
14 | break;
15 | }
16 | }
17 | }
18 |
19 | // Note: In the book, this is a code snippet. It lacks the "Using UnityEngine" statement.
--------------------------------------------------------------------------------
/Addendum/JobExample.cs:
--------------------------------------------------------------------------------
1 | // using Unity.Jobs;
2 | // using UnityEngine;
3 |
4 | // Needs Unity Job and Burst system installed
5 | /* public class JobExample : MonoBehaviour
6 | {
7 | private struct SimpleJob : IJob
8 | {
9 | public void Execute()
10 | {
11 | // Perform heavy computation here
12 | Debug.Log("Job executed!");
13 | }
14 | }
15 | void Start()
16 | {
17 | // Schedule the job to run on a worker thread
18 | SimpleJob job = new SimpleJob();
19 | JobHandle jobHandle = job.Schedule();
20 | jobHandle.Complete(); // Ensure the job is finished before
21 | proceeding
22 | }
23 | } /*
--------------------------------------------------------------------------------
/Chapter07/SettingsMenu.cs:
--------------------------------------------------------------------------------
1 | // SettingsMenu.cs
2 | using UnityEngine;
3 | using UnityEngine.UI; // Include the UI namespace
4 |
5 | public class SettingsMenu : MonoBehaviour
6 | {
7 | public Slider volumeSlider; // Reference to the volume slider
8 |
9 | void Start()
10 | {
11 | // Initialize the slider's value to the current game volume
12 | volumeSlider.value = AudioListener.volume;
13 | }
14 |
15 | public void SetVolume(float volume)
16 | {
17 | // Adjust the game's volume based on the slider's value
18 | AudioListener.volume = volume;
19 | }
20 | }
--------------------------------------------------------------------------------
/Chapter14/ARSetup.cs:
--------------------------------------------------------------------------------
1 | // ARSetup.cs
2 |
3 | // Needs AR Foundation package installed
4 |
5 | /* using UnityEngine;
6 | using UnityEngine.XR.ARFoundation;
7 | using UnityEngine.XR.ARSubsystems;
8 |
9 | public class ARSetup : MonoBehaviour
10 | {
11 | private ARSession arSession;
12 | private ARSessionOrigin arSessionOrigin;
13 |
14 | void Start()
15 | {
16 | arSession = GetComponent();
17 | arSessionOrigin = GetComponent();
18 |
19 | if (ARSession.state == ARSessionState.None)
20 | {
21 | arSession.enabled = true;
22 | }
23 | }
24 | } */
--------------------------------------------------------------------------------
/Chapter09/InventoryManager.cs:
--------------------------------------------------------------------------------
1 | // InventoryManager01.cs
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | public class InventoryManager : MonoBehaviour
6 | {
7 | // Dictionary to hold item IDs and their names
8 | Dictionary inventory = new Dictionary();
9 |
10 | void Start()
11 | {
12 | // Adding items to the dictionary
13 | inventory.Add(1, "Sword");
14 | inventory.Add(2, "Shield");
15 | inventory.Add(3, "Health Potion");
16 |
17 | // Displaying an item name by its ID
18 | Debug.Log("Item with ID 1: " + inventory[1]);
19 | }
20 | }
--------------------------------------------------------------------------------
/Chapter15/ResponsivePanel.cs:
--------------------------------------------------------------------------------
1 | // ResponsivePanel.cs
2 | using UnityEngine;
3 | using UnityEngine.UI;
4 |
5 | public class ResponsivePanel : MonoBehaviour
6 | {
7 | public RectTransform panel;
8 |
9 | void Update()
10 | {
11 | if (Screen.width > Screen.height) // Landscape mode
12 | {
13 | panel.anchorMin = new Vector2(0.25f, 0.25f);
14 | panel.anchorMax = new Vector2(0.75f, 0.75f);
15 | }
16 | else // Portrait mode
17 | {
18 | panel.anchorMin = new Vector2(0.1f, 0.1f);
19 | panel.anchorMax = new Vector2(0.9f, 0.9f);
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/Addendum/UIToolkitExample04.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using UnityEngine.UIElements;
3 |
4 | public class UIToolkitExample04 : MonoBehaviour
5 | {
6 | private void OnEnable()
7 | {
8 | var root = GetComponent().rootVisualElement;
9 |
10 | // Create a button and assign a class name for USS styling Button myButton = new Button();
11 | myButton.text = "Styled Button"; myButton.AddToClassList("myButton");
12 |
13 | // Add the button to the root element root.Add(myButton);
14 | root.Add(myButton);
15 |
16 | // Load the USS file
17 | var styleSheet = Resources.Load("buttonStyle"); root.styleSheets.Add(styleSheet);
18 | }
19 | }
--------------------------------------------------------------------------------
/Chapter04/GameManager01.cs:
--------------------------------------------------------------------------------
1 | // GameManager01.cs
2 | using UnityEngine;
3 |
4 | public class GameManager01 : MonoBehaviour
5 | {
6 | GameObject player;
7 | void Start()
8 | {
9 | // Player player = FindObjectOfType();
10 | if (player != null)
11 | {
12 | // Subscribe to the PowerUpCollected event
13 | //player.PowerUpCollected += HandlePowerUpCollected;
14 | }
15 | }
16 |
17 | // Method to handle the PowerUpCollected event
18 | void HandlePowerUpCollected()
19 | {
20 | Debug.Log("Player collected a power-up!");
21 | // Perform relevant actions
22 | }
23 | }
--------------------------------------------------------------------------------
/Chapter05/MyNetworkManager.cs:
--------------------------------------------------------------------------------
1 | // MyNetworkManager.cs
2 | using UnityEngine;
3 | //using Unity.Netcode;
4 | //Needs Unity's Netcode Package
5 |
6 | public class MyNetworkManager : MonoBehaviour
7 | //use NetworkManager after installing Netcode for Unity
8 | {
9 | //public override void
10 | // OnServerAddPlayer(NetworkConnection conn,
11 | // short playerControllerId)
12 | //{
13 | //GameObject player = Instantiate(playerPrefab,
14 | // Vector3.zero,
15 | // Quaternion.identity);
16 | //NetworkServer.AddPlayerForConnection(conn, player,
17 | // playerControllerId);
18 | //}
19 | }
--------------------------------------------------------------------------------
/Chapter03/DelegateExample.cs:
--------------------------------------------------------------------------------
1 | // DelegateExample.cs
2 |
3 | using System;
4 | using UnityEngine;
5 |
6 | public class DelegateExample
7 | {
8 | // Declare the delegate
9 | delegate int MathOperation(int a, int b);
10 |
11 | public static void Main()
12 | {
13 | // Instantiate the delegate with the Add method
14 | MathOperation op = Add;
15 |
16 | // Use the delegate to invoke the Add method;
17 | int result = op(10, 5);
18 | Debug.Log($"10 + 5 = {result}");
19 | }
20 |
21 | // Method matching the delegate signature
22 | static int Add( int x, int y)
23 | {
24 | return x + y;
25 | }
26 | }
--------------------------------------------------------------------------------
/Chapter15/VerticalList.cs:
--------------------------------------------------------------------------------
1 | // VerticalList.cs
2 | using UnityEngine;
3 | using UnityEngine.UI;
4 |
5 | public class VerticalList : MonoBehaviour
6 | {
7 | public GameObject buttonPrefab;
8 | public Transform contentParent;
9 |
10 | void Start()
11 | {
12 | // Instantiate multiple buttons and add them to the Vertical Layout Group
13 | for (int i = 0; i < 10; i++)
14 | {
15 | GameObject button = Instantiate(buttonPrefab,
16 | contentParent);
17 | button.GetComponentInChildren().text = "Button " +
18 | (i + 1);
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/Chapter06/ListExample02.cs:
--------------------------------------------------------------------------------
1 | // ListExample01.cs (version #2)
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | public class ListExample02 : MonoBehaviour
6 | {
7 | List scores = new List();
8 |
9 | void Start()
10 | {
11 | // Adding elements
12 | scores.Add(10);
13 | scores.Add(20);
14 |
15 | // Accessing elements
16 | Debug.Log("First score: " + scores[0]);
17 |
18 | // Iterating over the list
19 | foreach (int score in scores)
20 | {
21 | Debug.Log("Score: " + score);
22 | }
23 |
24 | // Removing elements
25 | scores.Remove(10);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Chapter11/GameActions.cs:
--------------------------------------------------------------------------------
1 | /* Must install the Unity.Netcode package from the Package Manager.
2 | using Unity.Netcode;
3 |
4 | public class GameActions : NetworkBehaviour {
5 | [ServerRpc]
6 | public void FireProjectileServerRpc()
7 | {
8 | PerformFire();
9 | FireProjectileClientRpc();
10 | }
11 |
12 | [ClientRpc]
13 | private void FireProjectileClientRpc() {
14 | // This method will be called on all clients
15 | if (!IsServer) // Avoid double execution on the server {
16 | PerformFire();
17 | }
18 | }
19 |
20 | void PerformFire(){
21 | // Code to instantiate and fire a projectile
22 |
23 | } */
24 |
25 |
--------------------------------------------------------------------------------
/Chapter06/InventoryManager01.cs:
--------------------------------------------------------------------------------
1 | // InventoryManager01.cs
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | public class InventoryManager01 : MonoBehaviour
6 | {
7 | List inventory = new List();
8 |
9 | public void AddItem(string item)
10 | {
11 | inventory.Add(item);
12 | }
13 |
14 | public void RemoveItem(string item)
15 | {
16 | inventory.Remove(item);
17 | }
18 |
19 | void Update()
20 | {
21 | if (Input.GetKeyDown(KeyCode.I))
22 | {
23 | foreach (var item in inventory)
24 | {
25 | Debug.Log("Inventory Item: " + item);
26 | }
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/Chapter10/UrbanCrowdMovement.cs:
--------------------------------------------------------------------------------
1 | // UrbanCrowdMovement.cs
2 | using UnityEngine;
3 | using UnityEngine.AI;
4 |
5 | public class UrbanCrowdMovement : MonoBehaviour
6 | {
7 | public Transform[] waypoints;
8 | private NavMeshAgent agent;
9 |
10 | void Start()
11 | {
12 | agent = GetComponent();
13 | agent.SetDestination(waypoints[Random.Range(0,
14 | waypoints.Length)].position);
15 | }
16 |
17 | void Update()
18 | {
19 | if (!agent.pathPending && agent.remainingDistance < 0.5f)
20 | {
21 | agent.SetDestination(waypoints[Random.Range(0,
22 | waypoints.Length)].position);
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/Chapter08/GravityAndImpulseDemo.cs:
--------------------------------------------------------------------------------
1 | // GravityAndImpulseDemo.cs
2 | using UnityEngine;
3 |
4 | public class GravityAndImpulseDemo : MonoBehaviour
5 | {
6 | public float jumpForce = 5f;
7 | private Rigidbody rb;
8 |
9 | void Start()
10 | {
11 | // Get the Rigidbody component attached to the GameObject
12 | rb = GetComponent();
13 | }
14 |
15 | void Update()
16 | {
17 | // Check for user input to apply an impulse force
18 | if (Input.GetKeyDown(KeyCode.Space))
19 | {
20 | // Apply an impulse force upwards to simulate a jump
21 | rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/Chapter06/InventoryManager02.cs:
--------------------------------------------------------------------------------
1 | // InventoryManager01.cs (Version 2)
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | public class InventoryManager02 : MonoBehaviour
6 | {
7 | Dictionary inventory = new Dictionary();
8 |
9 | void Start()
10 | {
11 | // Adding items to the inventory
12 | inventory.Add("Potion", 5);
13 | inventory.Add("Sword", 1);
14 | }
15 |
16 | void Update()
17 | {
18 | // Accessing and updating an item's quantity
19 | if (Input.GetKeyDown(KeyCode.U))
20 | {
21 | inventory["Potion"] += 1;
22 | Debug.Log("Potions: " + inventory["Potion"]);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Chapter08/InteractiveDoor.cs:
--------------------------------------------------------------------------------
1 | // InteractiveDoor.cs
2 | using UnityEngine;
3 |
4 | public class InteractiveDoor : MonoBehaviour
5 | {
6 | public Animator doorAnimator;
7 | public float interactionRange = 2f;
8 | GameObject player;
9 |
10 | private void Update()
11 | {
12 | // Check if the player is within the interaction range
13 | if (Vector3.Distance(transform.position, player.transform.position) <= interactionRange)
14 | {
15 | // Play the "Open" animation
16 | doorAnimator.SetTrigger("Open");
17 | }
18 | else
19 | {
20 | // Play the "Close" animation
21 | doorAnimator.SetTrigger("Close");
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/Addendum/PlayerController04.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 |
3 | using UnityEngine.InputSystem;
4 |
5 | public class PlayerController04 : MonoBehaviour
6 | {
7 | private Vector2 moveInput;
8 | public float speed = 5f;
9 | private CharacterController controller;
10 | private void Start(){
11 | controller = GetComponent();
12 | }
13 |
14 | // Input System event handler for the Move action
15 | public void OnMove(InputAction.CallbackContext context) {
16 | moveInput = context.ReadValue();
17 | }
18 | private void Update() {
19 | // Convert the input vector into movement and apply it
20 | Vector3 move = new Vector3(moveInput.x, 0, moveInput.y);
21 | controller.Move(move * speed * Time.deltaTime);
22 | }
23 | }
--------------------------------------------------------------------------------
/Chapter05/DayNightCycle.cs:
--------------------------------------------------------------------------------
1 | // DayNightCycle.cs
2 | using UnityEngine;
3 |
4 | public class DayNightCycle : MonoBehaviour
5 | {
6 | public Light directionalLight;
7 | public float dayLength;
8 | private float timeCounter = 0;
9 |
10 | void Update()
11 | {
12 | timeCounter += Time.deltaTime / dayLength;
13 |
14 | // Change light intensity and color based on timeCounter
15 | directionalLight.intensity = Mathf.Lerp(0.1f, 1,
16 | Mathf.Abs(Mathf.Cos(timeCounter * Mathf.PI *
17 | 2)));
18 | directionalLight.color = Color.Lerp(new Color(0.3f,
19 | 0.4f, 0.6f), Color.white,
20 | directionalLight.intensity);
21 | }
22 | }
--------------------------------------------------------------------------------
/Chapter14/AssetBundleLoader.cs:
--------------------------------------------------------------------------------
1 | // AssetBundleLoader.cs
2 | using UnityEngine;
3 | using System.Collections;
4 |
5 | public class AssetBundleLoader : MonoBehaviour
6 | {
7 | public string bundleURL;
8 | public string assetName;
9 |
10 | void Start()
11 | {
12 | StartCoroutine(LoadAssetBundle());
13 | }
14 |
15 | IEnumerator LoadAssetBundle()
16 | {
17 | using (WWW www = new WWW(bundleURL))
18 | {
19 | yield return www;
20 | AssetBundle bundle = www.assetBundle;
21 | if (bundle != null)
22 | {
23 | Instantiate(bundle.LoadAsset(assetName));
24 | bundle.Unload(false);
25 | }
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/Chapter05/PlayerMovement02.cs:
--------------------------------------------------------------------------------
1 | // PlayerMovement01.cs
2 | using UnityEngine;
3 | // using Unity.Netcode; Must install Unity.Netcode package first
4 |
5 | public class PlayerMovement02 : MonoBehaviour
6 | //NetworkBehaviour is expected when using Unity.Netcode
7 | {
8 | public float speed = 10f;
9 | bool isLocalPlayer = false;
10 | // Remove parameter isLocalPlayer after installing Unity.Netcode
11 |
12 | void Update()
13 | {
14 | if (!isLocalPlayer) return;
15 |
16 | float x = Input.GetAxis("Horizontal") * speed *
17 | Time.deltaTime;
18 | float z = Input.GetAxis("Vertical") * speed *
19 | Time.deltaTime;
20 | transform.Translate(x, 0, z);
21 | }
22 | }
--------------------------------------------------------------------------------
/Chapter08/CharacterPhysicsReactions.cs:
--------------------------------------------------------------------------------
1 | // CharacterPhysicsReactions.cs
2 | using UnityEngine;
3 |
4 | public class CharacterPhysicsReactions : MonoBehaviour
5 | {
6 | public Animator animator;
7 | public float stumbleForce = 5f;
8 |
9 | private void OnCollisionEnter(Collision collision)
10 | {
11 | // Check if the collision was with an obstacle
12 | if (collision.gameObject.tag == "Obstacle")
13 | {
14 | // Play the "stumble" animation
15 | animator.SetTrigger("Stumble");
16 |
17 | // Apply a force to the character to make them stumble
18 | GetComponent().AddForce(-collision.contacts[0].normal * stumbleForce, ForceMode.Impulse);
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/Chapter04/Health.cs:
--------------------------------------------------------------------------------
1 | // Health.cs
2 | using UnityEngine;
3 |
4 | public class Health : MonoBehaviour
5 | {
6 | public int healthPoints;
7 |
8 | // Getter method to retrieve healthPoints
9 | public int GetHealth()
10 | {
11 | return healthPoints;
12 | }
13 |
14 |
15 | // Setter method to update healthPoints
16 | public int SetHealth(int value)
17 | {
18 | healthPoints = value;
19 | return healthPoints;
20 | }
21 |
22 |
23 | // Method to apply damage to health
24 | public void TakeDamage(int damageAmount)
25 | {
26 | healthPoints -= damageAmount;
27 | Debug.Log("Player took " + damageAmount +
28 | " damage. Current health: " + healthPoints);
29 | }
30 | }
--------------------------------------------------------------------------------
/Chapter06/ArrayExample.cs:
--------------------------------------------------------------------------------
1 | // ArrayExample.cs
2 | using UnityEngine;
3 |
4 | public class ArrayExample : MonoBehaviour
5 | {
6 | // Array of positions for game objects
7 | public Vector3[] positions = new Vector3[5];
8 |
9 | void Start()
10 | {
11 | // Initialize positions
12 | for (int i = 0; i < positions.Length; i++)
13 | {
14 | positions[i] = new Vector3(i * 2.0f, 0, 0);
15 | }
16 | }
17 |
18 | void Update()
19 | {
20 | // Iterate over positions and update each
21 | for (int i = 0; i < positions.Length; i++)
22 | {
23 | // Example update: move each position upwards every frame
24 | positions[i] += Vector3.up * Time.deltaTime;
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Chapter04/ExampleScript.cs:
--------------------------------------------------------------------------------
1 | // ExampleScript.cs
2 | using UnityEngine;
3 |
4 | public class ExampleScript : MonoBehaviour
5 | {
6 | void Start()
7 | {
8 | // Accessing the AudioManager Singleton instance
9 | AudioManager audioManager = AudioManager.Instance;
10 |
11 | // Example usage: play a sound
12 | AudioClip soundClip =
13 | Resources.Load("ExampleSound");
14 | if (soundClip != null)
15 | {
16 | audioManager.PlaySound(soundClip);
17 | }
18 | else
19 | {
20 | Debug.Log("Sound clip not found!");
21 | }
22 | }
23 | }
24 |
25 | //Note: The text in the book has an extra bracket because it was shown as
26 | // part of a large file with multiple classes.
--------------------------------------------------------------------------------
/Chapter10/WildlifeBehavior.cs:
--------------------------------------------------------------------------------
1 | // WildlifeBehavior.cs
2 | using UnityEngine;
3 | using UnityEngine.AI;
4 |
5 | public class WildlifeBehavior : MonoBehaviour
6 | {
7 | public Transform[] roamPoints;
8 | private NavMeshAgent agent;
9 | private int destPoint = 0;
10 |
11 | void Start()
12 | {
13 | agent = GetComponent();
14 | GotoNextPoint();
15 | }
16 |
17 | void GotoNextPoint()
18 | {
19 | if (roamPoints.Length == 0)
20 | return;
21 |
22 | agent.destination = roamPoints[destPoint].position;
23 | destPoint = (destPoint + 1) % roamPoints.Length;
24 | }
25 |
26 | void Update()
27 | {
28 | if (!agent.pathPending && agent.remainingDistance < 0.5f)
29 | GotoNextPoint();
30 | }
31 | }
--------------------------------------------------------------------------------
/Chapter14/ARSceneSetup.cs:
--------------------------------------------------------------------------------
1 | // ARSceneSetup.cs
2 |
3 | // Needs AR Foundation package installed
4 |
5 | /* using UnityEngine;
6 | using UnityEngine.XR.ARFoundation;
7 | using UnityEngine.XR.ARSubsystems;
8 |
9 | public class ARSceneSetup : MonoBehaviour
10 | {
11 | private ARSession arSession;
12 | private ARSessionOrigin arSessionOrigin;
13 | private ARPlaneManager arPlaneManager;
14 |
15 | void Start()
16 | {
17 | arSession = FindObjectOfType();
18 | arSessionOrigin = FindObjectOfType();
19 | arPlaneManager = arSessionOrigin.GetComponent();
20 | }
21 |
22 | void Update()
23 | {
24 | if (arPlaneManager.trackables.count > 0)
25 | {
26 | Debug.Log("Planes detected.");
27 | }
28 | }
29 | } */
--------------------------------------------------------------------------------
/Chapter14/VRSetup.cs:
--------------------------------------------------------------------------------
1 | // VRSetup.cs
2 |
3 | // Need to add the XR Interaction Toolkit package
4 |
5 | /*
6 | using UnityEngine;
7 | using UnityEngine.XR.Management;
8 |
9 | public class VRSetup : MonoBehaviour
10 | {
11 | void Start()
12 | {
13 | XRGeneralSettings.Instance.Manager.InitializeLoaderSync();
14 | if (XRGeneralSettings.Instance.Manager.activeLoader == null)
15 | {
16 | Debug.LogError("Initializing XR failed.");
17 | }
18 | else
19 | {
20 | XRGeneralSettings.Instance.Manager.StartSubsystems();
21 | Debug.Log("XR Initialized.");
22 | }
23 | }
24 |
25 | void OnDisable()
26 | {
27 | XRGeneralSettings.Instance.Manager.StopSubsystems();
28 | XRGeneralSettings.Instance.Manager.DeinitializeLoader();
29 | }
30 | } */
--------------------------------------------------------------------------------
/Chapter04/Player02.cs:
--------------------------------------------------------------------------------
1 | // Player01.cs (version 2)
2 | using UnityEngine;
3 |
4 | public class Playe02 : MonoBehaviour
5 | {
6 | // Define a delegate type for the PowerUpCollected event
7 | public delegate void PowerUpCollectedEventHandler();
8 |
9 | // Define the event using the delegate type
10 | public event PowerUpCollectedEventHandler PowerUpCollected;
11 |
12 | void OnTriggerEnter(Collider other)
13 | {
14 | if (other.CompareTag("PowerUp"))
15 | {
16 | // Trigger the PowerUpCollected event
17 | OnPowerUpCollected();
18 | Destroy(other.gameObject); // Destroy the power-up object
19 | }
20 | }
21 |
22 | // Method to trigger the PowerUpCollected event
23 | protected virtual void OnPowerUpCollected()
24 | {
25 | PowerUpCollected?.Invoke();
26 | }
27 | }
--------------------------------------------------------------------------------
/Chapter10/EnemyController02.cs:
--------------------------------------------------------------------------------
1 | // EnemyController02.cs
2 | using UnityEngine; // Inserted for completeness
3 | public class EnemyController02 : MonoBehaviour
4 | {
5 | private Animator animator;
6 | private Transform player;
7 | private float detectionRange = 10.0f;
8 |
9 | void Start()
10 | {
11 | animator = GetComponent();
12 | player = GameObject.FindWithTag("Player").transform;
13 | }
14 |
15 | void Update()
16 | {
17 | float distanceToPlayer =
18 | Vector3.Distance(transform.position,
19 | player.position);
20 | if (distanceToPlayer < detectionRange)
21 | animator.SetTrigger("Chase");
22 | else
23 | animator.SetTrigger("Patrol");
24 | }
25 | }
26 |
27 | // Note: In the book, this is a code snippet. It lacks the "Using UnityEngine" statement.
--------------------------------------------------------------------------------
/Chapter13/Enemy02.cs:
--------------------------------------------------------------------------------
1 | // Enemy02.cs
2 | using UnityEngine;
3 |
4 | public class Enemy02 : MonoBehaviour
5 | {
6 | public float speed = 2f;
7 | private bool movingRight = true;
8 | public Transform groundDetection;
9 |
10 | void Update()
11 | {
12 | transform.Translate(Vector2.right * speed * Time.deltaTime);
13 |
14 | RaycastHit2D groundInfo =
15 | Physics2D.Raycast(groundDetection.position, Vector2.down, 2f);
16 | if (groundInfo.collider == false)
17 | {
18 | if (movingRight)
19 | {
20 | transform.eulerAngles = new Vector3(0, -180, 0);
21 | movingRight = false;
22 | }
23 | else
24 | {
25 | transform.eulerAngles = new Vector3(0, 0, 0);
26 | movingRight = true;
27 | }
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/Chapter10/EnemyPatrol.cs:
--------------------------------------------------------------------------------
1 | // EnemyPatrol.cs
2 | using UnityEngine;
3 | using UnityEngine.AI;
4 |
5 | public class EnemyPatrol : MonoBehaviour
6 | {
7 | public Transform[] patrolPoints;
8 | private NavMeshAgent agent;
9 | private int destPoint = 0;
10 |
11 | void Start()
12 | {
13 | agent = GetComponent();
14 | GotoNextPoint();
15 | }
16 |
17 | void GotoNextPoint()
18 | {
19 | if (patrolPoints.Length == 0)
20 | return;
21 |
22 | agent.destination = patrolPoints[destPoint].position;
23 | destPoint = (destPoint + 1) % patrolPoints.Length;
24 | }
25 |
26 | void Update()
27 | {
28 | if (!agent.pathPending && agent.remainingDistance < 0.5f)
29 | GotoNextPoint();
30 | }
31 |
32 | public void Investigate(Vector3 point)
33 | {
34 | agent.destination = point;
35 | }
36 | }
--------------------------------------------------------------------------------
/Chapter06/ListExample01.cs:
--------------------------------------------------------------------------------
1 | // ListExample01.cs
2 | using System.Collections.Generic;
3 | using UnityEngine;
4 |
5 | public class ListExample01 : MonoBehaviour
6 | {
7 | public List gameObjects;
8 |
9 | void Start()
10 | {
11 | gameObjects = new List();
12 | // Populate the list with game objects
13 | for (int i = 0; i < 5; i++)
14 | {
15 | GameObject obj = new GameObject("Object" + i);
16 | gameObjects.Add(obj);
17 | }
18 | }
19 |
20 | void Update()
21 | {
22 | // Example: Remove a game object from the list
23 | // when the 'R' key is pressed
24 | if (Input.GetKeyDown(KeyCode.R) && gameObjects.Count > 0)
25 | {
26 | GameObject objToRemove = gameObjects[0];
27 | gameObjects.Remove(objToRemove);
28 | Destroy(objToRemove);
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/Chapter10/UtilityDecider.cs:
--------------------------------------------------------------------------------
1 | // UtilityDecider.cs
2 | using UnityEngine; // Inserted for completeness
3 | public class UtilityDecider : MonoBehaviour
4 | {
5 | public float attackUtility;
6 | public float defendUtility;
7 | public float specialAbilityUtility;
8 |
9 | void DecideAction()
10 | {
11 | float maxUtility = Mathf.Max(attackUtility,
12 | defendUtility,
13 | specialAbilityUtility);
14 | if (maxUtility == attackUtility)
15 | PerformAttack();
16 | else if (maxUtility == defendUtility)
17 | PerformDefend();
18 | else
19 | PerformSpecialAbility();
20 | }
21 |
22 | void PerformAttack() { /* Implementation here */ }
23 | void PerformDefend() { /* Implementation here */ }
24 | void PerformSpecialAbility() { /* Implementation here */ }
25 | }
26 |
27 | // Note: In the book, this is a code snippet. It lacks the "Using UnityEngine" statement.
--------------------------------------------------------------------------------
/Chapter06/Point2DExample.cs:
--------------------------------------------------------------------------------
1 | // Point2DExample.cs
2 | using UnityEngine;
3 |
4 | public class Point2DExample : MonoBehaviour
5 | {
6 | void Start()
7 | {
8 | // Create an instance of Point2D
9 | Point2D point = new Point2D(3, 4);
10 |
11 | // Log the initial coordinates
12 | Debug.Log("Initial Point: (" + point.X + ", " +
13 | point.Y + ")");
14 |
15 | // Translate the point
16 | point.Translate(2, 3);
17 |
18 | // Log the new coordinates after translation
19 | Debug.Log("Translated Point: (" + point.X + ", " +
20 | point.Y + ")");
21 | }
22 | }
23 |
24 | public struct Point2D
25 | {
26 | public int X { get; set; }
27 | public int Y { get; set; }
28 |
29 | public Point2D(int x, int y)
30 | {
31 | X = x;
32 | Y = y;
33 | }
34 |
35 | public void Translate(int dx, int dy)
36 | {
37 | X += dx;
38 | Y += dy;
39 | }
40 | }
--------------------------------------------------------------------------------
/Chapter10/BattlefieldNavigation.cs:
--------------------------------------------------------------------------------
1 | // BattlefieldNavigation.cs
2 | using UnityEngine;
3 | using UnityEngine.AI;
4 |
5 | public class BattlefieldNavigation : MonoBehaviour
6 | {
7 | public Transform[] coverPoints;
8 | private NavMeshAgent agent;
9 |
10 | void Start()
11 | {
12 | agent = GetComponent();
13 | }
14 |
15 | public void FindCover()
16 | {
17 | Transform bestCover = coverPoints[0];
18 | float closestDistance =
19 | Vector3.Distance(transform.position, bestCover.position);
20 |
21 | foreach (Transform cover in coverPoints)
22 | {
23 | float distance = Vector3.Distance(transform.position,
24 | cover.position);
25 | if (distance < closestDistance)
26 | {
27 | closestDistance = distance;
28 | bestCover = cover;
29 | }
30 | }
31 |
32 | agent.destination = bestCover.position;
33 | }
34 | }
--------------------------------------------------------------------------------
/Chapter05/PlayerJump.cs:
--------------------------------------------------------------------------------
1 | // PlayerJump.cs
2 | using UnityEngine;
3 |
4 | public class PlayerJump : MonoBehaviour
5 | {
6 | public float jumpForce = 5f;
7 | private Rigidbody2D rb;
8 | private bool isGrounded;
9 |
10 | void Start()
11 | {
12 | rb = GetComponent();
13 | }
14 |
15 | void Update()
16 | {
17 | if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
18 | {
19 | rb.AddForce(new Vector2(0, jumpForce),
20 |
21 | ForceMode2D.Impulse);
22 | }
23 | }
24 |
25 | // Check if the player is touching the ground
26 | void OnCollisionEnter2D(Collision2D collision)
27 | {
28 | if (collision.gameObject.tag == "Ground")
29 | {
30 | isGrounded = true;
31 | }
32 | }
33 |
34 | void OnCollisionExit2D(Collision2D collision)
35 | {
36 | if (collision.gameObject.tag == "Ground")
37 | {
38 | isGrounded = false;
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/Chapter10/HideAndSeekAI.cs:
--------------------------------------------------------------------------------
1 | // HideAndSeekAI.cs
2 | using UnityEngine; // Inserted for completeness
3 | public class HideAndSeekAI : MonoBehaviour
4 | {
5 | public Transform player;
6 | private float decisionTime = 1.0f; // Time between decisions
7 | private float lastDecisionTime = 0f;
8 |
9 | void Update()
10 | {
11 | if (Time.time > lastDecisionTime + decisionTime)
12 | {
13 | MakeDecision();
14 | lastDecisionTime = Time.time;
15 | }
16 | }
17 |
18 | void MakeDecision()
19 | {
20 | if (Vector3.Distance(transform.position, player.position)
21 | < 10f)
22 | {
23 | // Logic to hide because the player is too close
24 | Debug.Log("Hiding");
25 | }
26 | else
27 | {
28 | // Logic to seek the player
29 | Debug.Log("Seeking");
30 | }
31 | }
32 | }
33 |
34 | // Note: In the book, this is a code snippet. It lacks the "Using UnityEngine" statement.
--------------------------------------------------------------------------------
/Chapter01/VariablesExample.cs:
--------------------------------------------------------------------------------
1 | // VariablesExample.cs
2 |
3 | using UnityEngine;
4 | public class VariablesExample : MonoBehaviour
5 | {
6 | // Start is called before the first frame update
7 | void Start()
8 | {
9 | // Integer variable
10 | int playerScore = 100;
11 |
12 | // Float variable
13 | float playerSpeed = 5.5f;
14 |
15 | // Double variable
16 | double playerHealth = 99.50009;
17 |
18 | // Boolean variable
19 | bool isGameOver = false;
20 |
21 | // Character variable
22 | char grade = 'A';
23 |
24 | // String variable
25 | string playerName = "Hero";
26 |
27 | // Output the values using Debug.Log
28 | Debug.Log("Player Name: " + playerName);
29 | Debug.Log("Score: " + playerScore);
30 | Debug.Log("Speed: " + playerSpeed);
31 | Debug.Log("Health: " + playerHealth);
32 | Debug.Log("Game Over: " + isGameOver);
33 | Debug.Log("Grade: " + grade);
34 | }
35 | }
--------------------------------------------------------------------------------
/Chapter08/ForceAndTorqueDemo.cs:
--------------------------------------------------------------------------------
1 | // ForceAndTorqueDemo.cs
2 | using UnityEngine;
3 |
4 | public class ForceAndTorqueDemo : MonoBehaviour
5 | {
6 | public float forceMagnitude = 10f;
7 | public float torqueMagnitude = 5f;
8 |
9 | private Rigidbody rb;
10 |
11 | void Start()
12 | {
13 | // Get the Rigidbody component attached to this GameObject
14 | rb = GetComponent();
15 | }
16 |
17 | void Update()
18 | {
19 | // Check for user input to apply force
20 | if (Input.GetKeyDown(KeyCode.Space))
21 | {
22 | // Apply an upward force to the Rigidbody
23 | rb.AddForce(Vector3.up * forceMagnitude,
24 | ForceMode.Impulse);
25 | }
26 |
27 | // Check for user input to apply torque
28 | if (Input.GetKeyDown(KeyCode.T))
29 | {
30 | // Apply a rotational force (torque) around the Z-axis
31 | rb.AddTorque(Vector3.forward * torqueMagnitude,
32 | ForceMode.Impulse);
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/Chapter09/ObjectPool.cs:
--------------------------------------------------------------------------------
1 | // ObjectPool.cs
2 |
3 | using System.Collections.Generic;
4 | using UnityEngine; // Inserted for completeness
5 | public class ObjectPool : MonoBehaviour
6 | {
7 | public GameObject prefab;
8 | public int poolSize = 10;
9 |
10 | private List pooledObjects;
11 |
12 | private void Start()
13 | {
14 | pooledObjects = new List();
15 |
16 | for (int i = 0; i < poolSize; i++)
17 | {
18 | GameObject obj = Instantiate(prefab);
19 | obj.SetActive(false);
20 | pooledObjects.Add(obj);
21 | }
22 | }
23 |
24 | public GameObject GetPooledObject()
25 | {
26 | foreach (GameObject obj in pooledObjects)
27 | {
28 | if (!obj.activeInHierarchy)
29 | {
30 | obj.SetActive(true);
31 | return obj;
32 | }
33 | }
34 | return null;
35 | }
36 | }
37 |
38 | // Note: In the book, these are code snippets. They lack the "Using UnityEngine" statement.
--------------------------------------------------------------------------------
/Chapter09/InvokeSendMessageCoroutineExample.cs:
--------------------------------------------------------------------------------
1 | // InvokeSendMessageCoroutineExample.cs
2 |
3 | using System.Collections;
4 | using UnityEngine;
5 |
6 | public class InvokeSendMessageCoroutineExample :
7 | MonoBehaviour
8 | {
9 | void Start()
10 | {
11 | Invoke("DelayedAction", 2.0f); // Using Invoke
12 | StartCoroutine(WaitAndPerformAction(3.0f));
13 | // Using Coroutine
14 | }
15 |
16 | void Update()
17 | {
18 | if (Input.GetKeyDown(KeyCode.Space))
19 | {
20 | SendMessage("PerformAction");
21 | // Using SendMessage
22 | }
23 | }
24 |
25 | void DelayedAction()
26 | {
27 | Debug.Log("Action performed after delay.");
28 | }
29 |
30 | IEnumerator WaitAndPerformAction(float delay)
31 | {
32 | yield return new WaitForSeconds(delay); // Waiting
33 | Debug.Log("Coroutine action performed after delay.");
34 | }
35 |
36 | void PerformAction()
37 | {
38 | Debug.Log("Action performed via SendMessage.");
39 | }
40 | }
--------------------------------------------------------------------------------
/Chapter15/SwipeControl.cs:
--------------------------------------------------------------------------------
1 | // SwipeControl.cs
2 | using UnityEngine;
3 |
4 | public class SwipeControl : MonoBehaviour
5 | {
6 | private Vector2 startTouchPosition, endTouchPosition;
7 | public float minSwipeDistance = 50f;
8 |
9 | void Update()
10 | {
11 | if (Input.touchCount > 0)
12 | {
13 | Touch touch = Input.GetTouch(0);
14 |
15 | if (touch.phase == TouchPhase.Began)
16 | {
17 | startTouchPosition = touch.position;
18 | }
19 | else if (touch.phase == TouchPhase.Ended)
20 | {
21 | endTouchPosition = touch.position;
22 | DetectSwipe();
23 | }
24 | }
25 | }
26 |
27 | void DetectSwipe()
28 | {
29 | if (Vector2.Distance(startTouchPosition, endTouchPosition) >=
30 | minSwipeDistance)
31 | {
32 | Vector2 swipeDirection = endTouchPosition -
33 | startTouchPosition;
34 | // Implement your swipe action based on swipeDirection
35 | }
36 | }
37 | }
--------------------------------------------------------------------------------
/Chapter10/NPCAgent.cs:
--------------------------------------------------------------------------------
1 | // NPCAgent.cs
2 |
3 | // Needs Unity.MLAgents package installed
4 |
5 | /*using Unity.MLAgents;
6 | using Unity.MLAgents.Sensors;
7 | using Unity.MLAgents.Actuators;
8 |
9 | public class NPCAgent : Agent
10 | {
11 | public override void OnEpisodeBegin()
12 | {
13 | // Reset the NPC state for new episode
14 | }
15 |
16 | public override void CollectObservations(VectorSensor sensor)
17 | {
18 | // Add NPC's observations of the environment
19 | for decision making
20 | }
21 |
22 | public override void OnActionReceived(ActionBuffers actionBuffers)
23 | {
24 | // Actions received from the model
25 | int action = actionBuffers.DiscreteActions[0];
26 | if (action == 1)
27 | {
28 | // Perform the action, e.g., move towards a target
29 | }
30 | }
31 |
32 | public override void Heuristic(in ActionBuffers actionsOut)
33 | {
34 | // Provide manual control as fallback
35 | actionsOut.DiscreteActions.Array[0] =
36 | Convert.ToInt32(Input.GetKey(KeyCode.Space));
37 | }
38 | } */
--------------------------------------------------------------------------------
/Chapter13/PlayerMovement.cs:
--------------------------------------------------------------------------------
1 | // PlayerMovement01.cs
2 | using UnityEngine;
3 |
4 | public class PlayerMovement : MonoBehaviour
5 | {
6 | public float speed = 5f;
7 | public float jumpForce = 7f;
8 | private Rigidbody2D rb;
9 | private bool isGrounded;
10 |
11 | void Start()
12 | {
13 | rb = GetComponent();
14 | }
15 |
16 | void Update()
17 | {
18 | float moveInput = Input.GetAxis("Horizontal");
19 | rb.linearVelocity = new Vector2(moveInput * speed, rb.linearVelocity.y);
20 |
21 | if (isGrounded && Input.GetKeyDown(KeyCode.Space))
22 | {
23 | rb.linearVelocity = Vector2.up * jumpForce;
24 | }
25 | }
26 |
27 | private void OnCollisionEnter2D(Collision2D collision)
28 | {
29 | if (collision.gameObject.CompareTag("Ground"))
30 | {
31 | isGrounded = true;
32 | }
33 | }
34 |
35 | private void OnCollisionExit2D(Collision2D collision)
36 | {
37 | if (collision.gameObject.CompareTag("Ground"))
38 | {
39 | isGrounded = false;
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Packt
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Chapter04/AudioManager.cs:
--------------------------------------------------------------------------------
1 | // AudioManager.cs
2 | using UnityEngine;
3 |
4 | public class AudioManager : MonoBehaviour
5 | {
6 | // Singleton instance
7 | private static AudioManager _instance;
8 |
9 | // Public accessor for the singleton instance
10 | public static AudioManager Instance
11 | {
12 | get
13 | {
14 | if (_instance == null)
15 | {
16 | _instance =
17 | FindObjectOfType();
18 | if (_instance == null)
19 | {
20 | GameObject singletonObject =
21 | new GameObject(typeof(AudioManager).Name);
22 | _instance =
23 | singletonObject.AddComponent();
24 | }
25 | }
26 | return _instance;
27 | }
28 | }
29 |
30 | // Private constructor to prevent external
31 | // instantiation
32 | private AudioManager() { }
33 |
34 |
35 | // Example method
36 | public void PlaySound(AudioClip clip)
37 | {
38 | // Play sound logic
39 | }
40 | }
--------------------------------------------------------------------------------
/Chapter09/PreferencesManager.cs:
--------------------------------------------------------------------------------
1 | // PreferencesManager.cs
2 | using UnityEngine;
3 |
4 | [System.Serializable]
5 | public class PlayerPreferences
6 | {
7 | public float audioVolume;
8 | public int brightness;
9 | public bool subtitlesEnabled;
10 | }
11 |
12 | public class PreferencesManager : MonoBehaviour
13 | {
14 | void Start()
15 | {
16 | PlayerPreferences prefs = new PlayerPreferences()
17 | {
18 | audioVolume = 0.8f,
19 | brightness = 50,
20 | subtitlesEnabled = true
21 | };
22 |
23 | // Serialize the PlayerPreferences object to a JSON string
24 | string prefsJson = JsonUtility.ToJson(prefs);
25 | Debug.Log("Serialized JSON: " + prefsJson);
26 |
27 | // Deserialize the JSON string back to a new PlayerPreferences object
28 | PlayerPreferences loadedPrefs = JsonUtility.FromJson(prefsJson);
29 | Debug.Log("Loaded Preferences: " + "Audio Volume - " + loadedPrefs.audioVolume +
30 | ", Brightness - " + loadedPrefs.brightness +
31 | ", Subtitles Enabled - " + loadedPrefs.subtitlesEnabled);
32 | }
33 | }
--------------------------------------------------------------------------------
/Chapter14/ARInteraction.cs:
--------------------------------------------------------------------------------
1 | // ARInteraction.cs
2 |
3 | // Needs AR Foundation package installed
4 |
5 | /* using UnityEngine;
6 | using UnityEngine.XR.ARFoundation;
7 | using UnityEngine.XR.ARSubsystems;
8 | using System.Collections.Generic;
9 |
10 | public class ARInteraction : MonoBehaviour
11 | {
12 | public GameObject objectToPlace;
13 | private ARRaycastManager arRaycastManager;
14 | private List hits = new List();
15 |
16 | void Start()
17 | {
18 | arRaycastManager = FindObjectOfType();
19 | }
20 |
21 | void Update()
22 | {
23 | if (Input.touchCount > 0)
24 | {
25 | Touch touch = Input.GetTouch(0);
26 | if (touch.phase == TouchPhase.Began)
27 | {
28 | if (arRaycastManager.Raycast(touch.position, hits,
29 | TrackableType.PlaneWithinPolygon))
30 | {
31 | Pose hitPose = hits[0].pose;
32 | Instantiate(objectToPlace, hitPose.position,
33 | hitPose.rotation);
34 | }
35 | }
36 | }
37 | }
38 | } */
--------------------------------------------------------------------------------
/Chapter08/BridgeCollapse.cs:
--------------------------------------------------------------------------------
1 | // BridgeCollapse.cs
2 | using UnityEngine;
3 |
4 | public class BridgeCollapse : MonoBehaviour
5 | {
6 | public float maxWeight = 500f;
7 | public float collapseSpeed = 2f;
8 | public Animator bridgeAnimator;
9 |
10 | private void OnTriggerEnter(Collider other)
11 | {
12 | // Check if the colliding object is the player
13 | if (other.CompareTag("Player"))
14 | {
15 | // Get the total weight of the player and any carried objects
16 | float totalWeight = other.GetComponent().mass; // + other.GetComponent().totalWeight;
17 | // Need to previously defined a PlayerInventory class with a totalWeight property
18 |
19 | // If the total weight exceeds the bridge's capacity,
20 | //start the collapse
21 | if (totalWeight > maxWeight)
22 | {
23 | bridgeAnimator.SetTrigger("Collapse");
24 | }
25 | }
26 | }
27 |
28 | private void Update()
29 | {
30 | // Gradually lower the bridge as it collapses
31 | transform.Translate(collapseSpeed * Time.deltaTime * Vector3.down);
32 | }
33 | }
--------------------------------------------------------------------------------
/Chapter15/ResponsiveButton.cs:
--------------------------------------------------------------------------------
1 | // ResponsiveButton.cs
2 | using UnityEngine;
3 | using UnityEngine.UI;
4 |
5 | public class ResponsiveButton : MonoBehaviour
6 | {
7 | public CanvasScaler canvasScaler;
8 | public Button myButton;
9 |
10 | void Start()
11 | {
12 | // Configure the Canvas Scaler for resolution independence
13 | canvasScaler.uiScaleMode =
14 | CanvasScaler.ScaleMode.ScaleWithScreenSize;
15 | canvasScaler.referenceResolution = new Vector2(1920, 1080);
16 |
17 | // Set up the button's Rect Transform to anchor to the bottom-right corner
18 | RectTransform buttonRectTransform =
19 | myButton.GetComponent();
20 | buttonRectTransform.anchorMin = new Vector2(1, 0);
21 | buttonRectTransform.anchorMax = new Vector2(1, 0);
22 | buttonRectTransform.pivot = new Vector2(1, 0);
23 | buttonRectTransform.anchoredPosition = new Vector2(-50, 50);
24 |
25 | // Add an onClick listener to provide haptic feedback
26 | myButton.onClick.AddListener(TriggerHapticFeedback);
27 | }
28 |
29 | void TriggerHapticFeedback()
30 | {
31 | if (SystemInfo.supportsVibration)
32 | {
33 | Handheld.Vibrate();
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/Chapter10/PatrolGuardAI.cs:
--------------------------------------------------------------------------------
1 | // PatrolGuardAI.cs
2 |
3 | using System.Collections.Generic;
4 | using UnityEditor.Experimental.GraphView;
5 | using UnityEngine; // Inserted for completeness
6 | public class PatrolGuardAI : MonoBehaviour
7 | {
8 | // This is indeed for visual display in Unity's Behavior Tree window.
9 |
10 | /*private BehaviorTree tree;
11 |
12 | void Start()
13 | {
14 | tree = new BehaviorTree();
15 |
16 | Node root = new SelectorNode();
17 | Node patrolNode = new SequenceNode(new List
18 | {
19 | new CheckPatrolAreaNode(),
20 | new MoveToNode(patrolPath),
21 | });
22 | Node chaseNode = new SequenceNode(new List
23 | {
24 | new CanSeePlayerNode(),
25 | new ChasePlayerNode(),
26 | });
27 | Node investigateNode = new SequenceNode(new List
28 | {
29 | new HeardNoiseNode(),
30 | new InvestigateNoiseNode(),
31 | });
32 |
33 | root.AddChild(patrolNode);
34 | root.AddChild(chaseNode);
35 | root.AddChild(investigateNode);
36 |
37 | tree.SetRoot(root);
38 | }
39 |
40 | void Update()
41 | {
42 | tree.Tick(); // Process the behavior tree
43 | }*/
44 |
45 | }
--------------------------------------------------------------------------------
/Chapter10/EnemyController03.cs:
--------------------------------------------------------------------------------
1 | // EnemyController03.cs
2 | using UnityEngine; // Inserted for completeness
3 | public interface IEnemyState {
4 | void EnterState(EnemyController02 controller);
5 | void UpdateState();
6 | }
7 |
8 | public class PatrolState : IEnemyState {
9 | public void EnterState(EnemyController02 controller) {
10 | //controller.SetPatrolBehavior();
11 | }
12 |
13 | public void UpdateState() {
14 | // Patrol logic here
15 | }
16 | }
17 |
18 | public class AttackState : IEnemyState {
19 | public void EnterState(EnemyController02 controller) {
20 | //controller.SetAttackBehavior();
21 | }
22 |
23 | public void UpdateState() {
24 | // Attack logic here
25 | }
26 | }
27 |
28 | public class EnemyController : MonoBehaviour {
29 | private IEnemyState currentState;
30 |
31 | public void SetState(IEnemyState newState) {
32 | currentState = newState;
33 | //currentState.EnterState(this);
34 | }
35 |
36 | void Update() {
37 | currentState.UpdateState();
38 | }
39 |
40 | public void SetPatrolBehavior() {
41 | // Specific patrol settings
42 | }
43 |
44 | public void SetAttackBehavior() {
45 | // Specific attack settings
46 | }
47 | }
48 |
49 | // Note: In the book, this is a code snippet. It lacks the "Using UnityEngine" statement.
--------------------------------------------------------------------------------
/Chapter05/TerrainDeformer.cs:
--------------------------------------------------------------------------------
1 | // TerrainDeformer.cs
2 | using UnityEngine;
3 |
4 | public class TerrainDeformer : MonoBehaviour
5 | {
6 | public Terrain terrain;
7 | private TerrainData terrainData;
8 | private float[,] originalHeightMap;
9 |
10 | void Start()
11 | {
12 | terrainData = terrain.terrainData;
13 |
14 | originalHeightMap = terrainData.GetHeights(0, 0,
15 | terrainData.heightmapResolution,
16 | terrainData.heightmapResolution);
17 | }
18 |
19 | void Update()
20 | {
21 | Vector3 playerPosition = transform.position;
22 | Vector3Int terrainPosition = new Vector3Int(
23 | Mathf.RoundToInt(playerPosition.x),
24 | Mathf.RoundToInt(playerPosition.y),
25 | Mathf.RoundToInt(playerPosition.z)
26 | );
27 |
28 | // Deform terrain under player
29 | // Note: This is a simplified example. In practice,
30 | // you’ll need to convert the player's position to
31 | // terrain’s local space and modify a range of
32 | // heights around the player.
33 | terrainData.SetHeights(terrainPosition.x,
34 | terrainPosition.z,
35 | new float[,] { { 0.5f } });
36 | }
37 |
38 | void OnDestroy()
39 | {
40 | // Restore the original terrain heights when the
41 | // script is destroyed
42 | terrainData.SetHeights(0, 0, originalHeightMap);
43 | }
44 | }
--------------------------------------------------------------------------------
/.idea/.idea.B22128_Chapter_CodeSamples.dir/.idea/cody_history.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # A-Unity-Developer-s-guide-to-C-scripting
2 | A Unity Developer's guide to C# scripting, Published by Packt
3 |
4 | # Part 1: Foundational Concepts
5 |
6 | Chapter 1, Getting Started with Unity and C#: Game Objects and Components.
7 |
8 | Chapter 2, Creating Your First Unity Project: Mastering Scenes and Assets
9 |
10 | Chapter 3, C# Fundamentals in Unity: Variables, Loops, and Troubleshooting Techniques
11 |
12 | Chapter 4, Exploring Unity's Scripting Anatomy: MonoBehavior, Lifecycle, User Inputs, and Inter-Script Communications
13 |
14 |
15 | # Part 2: Intermediate Concepts
16 |
17 | Chapter 5, Mastering Unity's API: Physics, Collisions, and Environment Interaction
18 |
19 | Chapter 6, Data Structures in Unity: Arrays, Lists, Dictionaries, HashSets, and Game Logic Implementation
20 |
21 | Chapter 7, Designing Interactive UI Elements: Menus and Player Interactions in Unity
22 |
23 | Chapter 8, Mastering Physics and Animation in Unity Game Development
24 |
25 |
26 | # Part 3: Advanced Game Development
27 |
28 | Chapter 9, Advanced Scripting Techniques in Unity: Async, Cloud Integration, Events, and Optimizing
29 |
30 | Chapter 10, Implementing Artificial Intelligence in Unity: Pathfinding and Behavior Trees
31 |
32 | Chapter 11, Multiplayer and Networking : Matchmaking, Security, and Interactive Gameplay
33 |
34 | Chapter 12, Optimizing Game Performance in Unity: Profiling and Analysis Techniques
35 |
36 |
37 | # Part 4: Real World Applications
and Case Studies
38 |
39 | Chapter 13, Building a Complete Game in Unity: Core Mechanics, Testing, and Enhancing Player Experience
40 |
41 | Chapter 14, Exploring XR in Unity: Developing Virtual and Augmented Reality Experiences
42 |
43 | Chapter 15, Cross-Platform Game Development in Unity: Mobile, Desktop, and Console
44 |
45 | Chapter 16, Publishing, Monetizing, and Marketing Your Game in Unity: Strategies for Advertising and Community Building
46 |
47 |
--------------------------------------------------------------------------------