Guest User

Escape The Island - ChatGPT Transcript

a guest
Mar 27th, 2023
1,103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 59.34 KB | None | 0 0
  1. Let's make a game together. Give me an idea of a 3D game to create
  2. --------------------------
  3. Sure, here's an idea for a 3D game:
  4.  
  5. Title: "Escape the Island"
  6.  
  7. Gameplay: The player is stranded on a deserted island and must find a way to escape. The island is full of dangers such as wild animals, treacherous terrain, and harsh weather conditions. The player must explore the island, gather resources, and solve puzzles to find a way off the island. Along the way, the player will encounter other stranded individuals who may be able to provide assistance or hinder progress.
  8.  
  9. Game Mechanics:
  10.  
  11. Exploration - The player must explore the island to find resources, clues, and items that will help them escape.
  12.  
  13. Resource Management - The player must manage their resources carefully, including food, water, and shelter.
  14.  
  15. Crafting - The player can use the resources they find to craft tools, weapons, and other useful items.
  16.  
  17. Puzzle-Solving - The player will encounter puzzles that must be solved to progress through the game.
  18.  
  19. Survival - The player must avoid danger and maintain their health and energy levels in order to survive.
  20.  
  21. Social Interaction - The player will encounter other characters on the island and must interact with them to gain information, assistance, or items.
  22.  
  23. Objective: The objective of the game is to escape the island by finding a way to signal for rescue, repairing a boat, or finding another means of escape.
  24.  
  25. I hope this idea inspires you to create an exciting and engaging 3D game!
  26. --------------------------
  27. I like this idea. Could you give me a script to move the player around ? It has to be in first person
  28. --------------------------
  29. Certainly! Here is an example script for moving the player around in a first-person perspective:
  30.  
  31. csharp
  32. Copy code
  33. using UnityEngine;
  34.  
  35. public class PlayerMovement : MonoBehaviour
  36. {
  37. public float moveSpeed = 5f; // speed at which the player moves
  38. public float jumpForce = 10f; // force of the player's jump
  39. public Transform groundCheck; // object representing the position of the ground check
  40. public float groundDistance = 0.4f; // distance from the ground check object to the ground
  41. public LayerMask groundMask; // layers that represent the ground
  42.  
  43. Rigidbody rb;
  44. bool isGrounded = true;
  45.  
  46. void Start()
  47. {
  48. rb = GetComponent<Rigidbody>();
  49. }
  50.  
  51. void Update()
  52. {
  53. // get input for player movement
  54. float horizontal = Input.GetAxisRaw("Horizontal");
  55. float vertical = Input.GetAxisRaw("Vertical");
  56.  
  57. // calculate movement vector
  58. Vector3 movement = transform.right * horizontal + transform.forward * vertical;
  59. movement = movement.normalized * moveSpeed * Time.deltaTime;
  60.  
  61. // move the player
  62. rb.MovePosition(transform.position + movement);
  63.  
  64. // check if player is on the ground
  65. isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
  66.  
  67. // allow the player to jump if on the ground and spacebar is pressed
  68. if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
  69. {
  70. rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
  71. isGrounded = false;
  72. }
  73. }
  74. }
  75.  
  76.  
  77. This script sets up basic movement for the player using the Rigidbody.MovePosition method to move the player in the direction of the input. It also allows the player to jump using a simple sphere cast to check if they are on the ground. Feel free to adjust the moveSpeed and jumpForce variables to your liking!
  78. --------------------------
  79. The camera is not following the player, how could I do that ?
  80. --------------------------
  81. To make the camera follow the player, you can use a Camera component and attach it to an empty GameObject that is a child of the player's GameObject. This empty GameObject will act as the camera's target, and the camera will move with it. Here's an example script that implements this:
  82.  
  83. csharp
  84. Copy code
  85. using UnityEngine;
  86.  
  87. public class CameraFollow : MonoBehaviour
  88. {
  89. public Transform target; // player's Transform component
  90. public float smoothSpeed = 0.125f; // how smoothly the camera follows the player
  91. public Vector3 offset; // offset of the camera from the player
  92.  
  93. void FixedUpdate()
  94. {
  95. // calculate target position for the camera
  96. Vector3 desiredPosition = target.position + offset;
  97.  
  98. // smoothly move the camera to the target position
  99. Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
  100. transform.position = smoothedPosition;
  101.  
  102. // make the camera always face the player
  103. transform.LookAt(target);
  104. }
  105. }
  106.  
  107.  
  108. Attach this script to the Camera object and set the target variable to the player's Transform component. The smoothSpeed variable controls how smoothly the camera follows the player, and the offset variable controls the distance between the player and the camera. You can adjust these variables to your liking.
  109. --------------------------
  110. The camera should move around with the mouse, how could I do that ?
  111. --------------------------
  112. To make the camera move around with the mouse, you can use the Input.GetAxis function to get the mouse input, and rotate the camera around the player based on that input. Here's an example script that implements this:
  113.  
  114. csharp
  115. Copy code
  116. using UnityEngine;
  117.  
  118. public class CameraFollow : MonoBehaviour
  119. {
  120. public Transform target; // player's Transform component
  121. public float smoothSpeed = 0.125f; // how smoothly the camera follows the player
  122. public Vector3 offset; // offset of the camera from the player
  123. public float rotationSpeed = 100f; // how fast the camera rotates around the player
  124.  
  125. float mouseX, mouseY;
  126.  
  127. void LateUpdate()
  128. {
  129. // get mouse input for camera rotation
  130. mouseX += Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime;
  131. mouseY -= Input.GetAxis("Mouse Y") * rotationSpeed * Time.deltaTime;
  132. mouseY = Mathf.Clamp(mouseY, -80f, 80f); // clamp vertical rotation to prevent camera flipping
  133.  
  134. // calculate rotation for camera
  135. Quaternion rotation = Quaternion.Euler(mouseY, mouseX, 0f);
  136.  
  137. // calculate target position for the camera
  138. Vector3 desiredPosition = target.position + offset;
  139.  
  140. // apply rotation to offset
  141. desiredPosition = rotation * offset;
  142.  
  143. // smoothly move the camera to the target position
  144. Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
  145. transform.position = smoothedPosition;
  146.  
  147. // make the camera always face the player
  148. transform.LookAt(target);
  149. }
  150. }
  151.  
  152.  
  153. Attach this script to the Camera object and set the target variable to the player's Transform component. The smoothSpeed and offset variables work the same as in the previous script. The rotationSpeed variable controls how fast the camera rotates around the player. The mouseX and mouseY variables track the mouse input for rotation. The Mathf.Clamp function is used to limit the vertical rotation to prevent the camera from flipping over.
  154. --------------------------
  155. This really does not work as intented. Let's start again, I'd like a script for Unity allowing me to move a first person character around the scene. We also need a camera system that follows the mouse movements
  156. --------------------------
  157. Sure, here's a new script that allows the player to move in a first-person view, with a camera that follows the mouse movements:
  158.  
  159. csharp
  160. Copy code
  161. using UnityEngine;
  162.  
  163. public class PlayerMovement : MonoBehaviour
  164. {
  165. public float moveSpeed = 5f;
  166. public float mouseSensitivity = 100f;
  167.  
  168. float verticalRotation = 0f;
  169. CharacterController controller;
  170.  
  171. void Start()
  172. {
  173. controller = GetComponent<CharacterController>();
  174. Cursor.lockState = CursorLockMode.Locked;
  175. }
  176.  
  177. void Update()
  178. {
  179. // Get player input for movement
  180. float x = Input.GetAxis("Horizontal");
  181. float z = Input.GetAxis("Vertical");
  182.  
  183. // Calculate movement vector based on input
  184. Vector3 move = transform.right * x + transform.forward * z;
  185.  
  186. // Move the character controller
  187. controller.Move(move * moveSpeed * Time.deltaTime);
  188.  
  189. // Get player input for rotation
  190. float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
  191. float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
  192.  
  193. // Rotate the character horizontally
  194. transform.Rotate(Vector3.up * mouseX);
  195.  
  196. // Calculate vertical rotation and apply to camera
  197. verticalRotation -= mouseY;
  198. verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
  199. Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
  200. }
  201. }
  202.  
  203.  
  204. Attach this script to the player's GameObject. The moveSpeed variable controls how fast the player moves, and the mouseSensitivity variable controls how fast the camera rotates. The Start method gets the CharacterController component and locks the mouse cursor to the game window. The Update method handles player input for movement and rotation. The controller.Move method moves the character controller based on the input. The transform.Rotate method rotates the character horizontally based on mouse input. Finally, the script calculates the vertical rotation based on mouse input and applies it to the camera using Camera.main.transform.localRotation.
  205. --------------------------
  206. That works ! How do I make the player affected by gravity ?
  207. --------------------------
  208. To make the player affected by gravity, you can add a Gravity variable to the script and apply it to the player's CharacterController component in the Update method. Here's an updated script that includes gravity:
  209.  
  210. csharp
  211. Copy code
  212. using UnityEngine;
  213.  
  214. public class PlayerMovement : MonoBehaviour
  215. {
  216. public float moveSpeed = 5f;
  217. public float mouseSensitivity = 100f;
  218. public float gravity = -9.81f;
  219.  
  220. float verticalRotation = 0f;
  221. CharacterController controller;
  222.  
  223. void Start()
  224. {
  225. controller = GetComponent<CharacterController>();
  226. Cursor.lockState = CursorLockMode.Locked;
  227. }
  228.  
  229. void Update()
  230. {
  231. // Get player input for movement
  232. float x = Input.GetAxis("Horizontal");
  233. float z = Input.GetAxis("Vertical");
  234.  
  235. // Calculate movement vector based on input
  236. Vector3 move = transform.right * x + transform.forward * z;
  237.  
  238. // Apply gravity to movement
  239. move.y = gravity;
  240.  
  241. // Move the character controller
  242. controller.Move(move * moveSpeed * Time.deltaTime);
  243.  
  244. // Get player input for rotation
  245. float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
  246. float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
  247.  
  248. // Rotate the character horizontally
  249. transform.Rotate(Vector3.up * mouseX);
  250.  
  251. // Calculate vertical rotation and apply to camera
  252. verticalRotation -= mouseY;
  253. verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
  254. Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
  255. }
  256. }
  257.  
  258.  
  259. In this updated script, the gravity variable controls the strength of the gravity. In the Update method, the script
  260. --------------------------
  261. Perfect, the player now needs to be able to interact with other objects. He needs to be able to pick up objects and store them in his inventory
  262. --------------------------
  263. To allow the player to pick up objects and store them in their inventory, you can create a new script that will handle the interaction between the player and the objects.
  264.  
  265. Here's an example script that allows the player to pick up objects by pressing the "E" key, and stores them in a list that represents the player's inventory:
  266.  
  267. csharp
  268. Copy code
  269. using UnityEngine;
  270. using System.Collections.Generic;
  271.  
  272. public class PlayerInventory : MonoBehaviour
  273. {
  274. public float maxPickupDistance = 2f;
  275. public KeyCode pickupKey = KeyCode.E;
  276. public List<GameObject> inventory = new List<GameObject>();
  277. private GameObject itemHeld;
  278.  
  279. void Update()
  280. {
  281. // Check if player presses pickup key
  282. if (Input.GetKeyDown(pickupKey))
  283. {
  284. // Check if there's an object in front of the player that can be picked up
  285. RaycastHit hit;
  286. if (Physics.Raycast(transform.position, transform.forward, out hit, maxPickupDistance))
  287. {
  288. // Check if the object has a "Pickupable" tag
  289. if (hit.collider.CompareTag("Pickupable"))
  290. {
  291. // Add the object to the player's inventory
  292. inventory.Add(hit.collider.gameObject);
  293. // Remove the object from the scene
  294. hit.collider.gameObject.SetActive(false);
  295. }
  296. }
  297. }
  298.  
  299. // Check if player is holding an item and presses pickup key again to drop it
  300. if (Input.GetKeyDown(pickupKey) && itemHeld != null)
  301. {
  302. // Drop the item
  303. itemHeld.SetActive(true);
  304. itemHeld.transform.position = transform.position + transform.forward * 1.5f;
  305. itemHeld = null;
  306. }
  307.  
  308. // Check if player presses number keys to select items in inventory
  309. for (int i = 0; i < inventory.Count; i++)
  310. {
  311. if (Input.GetKeyDown((i + 1).ToString()))
  312. {
  313. // Drop any item that is currently being held
  314. if (itemHeld != null)
  315. {
  316. itemHeld.SetActive(true);
  317. itemHeld.transform.position = transform.position + transform.forward * 1.5f;
  318. }
  319.  
  320. // Select the item in inventory and remove it from inventory list
  321. itemHeld = inventory[i];
  322. inventory.RemoveAt(i);
  323. break;
  324. }
  325. }
  326. }
  327. }
  328.  
  329.  
  330. Attach this script to the player's GameObject. The maxPickupDistance variable controls how far the player can reach to pick up an object. The pickupKey variable controls which key the player needs to press to pick up an object. The inventory list represents the player's inventory, which is initially empty. The itemHeld variable represents the object that the player is currently holding.
  331.  
  332. In the Update method, the script checks if the player is pressing the pickup key. If there's an object in front of the player that can be picked up, the object is added to the player's inventory and removed from the scene. If the player is holding an item and presses the pickup key again, the item is dropped in front of the player. The script also allows the player to select items in their inventory by pressing the number keys. When an item is selected, it is removed from the inventory list and held by the player. When the player drops an item, it is placed in front of the player at a distance of 1.5 units.
  333. --------------------------
  334. I think we should also use a LayerMask system to ignore certains objects that could get in our way. Could you add this functionnality in the same script ?
  335. --------------------------
  336. Sure! Here's an updated version of the script that includes a LayerMask to ignore certain objects:
  337.  
  338. csharp
  339. Copy code
  340. using UnityEngine;
  341. using System.Collections.Generic;
  342.  
  343. public class PlayerInventory : MonoBehaviour
  344. {
  345. public float maxPickupDistance = 2f;
  346. public KeyCode pickupKey = KeyCode.E;
  347. public List<GameObject> inventory = new List<GameObject>();
  348. private GameObject itemHeld;
  349. public LayerMask ignoreLayer;
  350.  
  351. void Update()
  352. {
  353. // Check if player presses pickup key
  354. if (Input.GetKeyDown(pickupKey))
  355. {
  356. // Check if there's an object in front of the player that can be picked up
  357. RaycastHit hit;
  358. if (Physics.Raycast(transform.position, transform.forward, out hit, maxPickupDistance, ~ignoreLayer))
  359. {
  360. // Check if the object has a "Pickupable" tag
  361. if (hit.collider.CompareTag("Pickupable"))
  362. {
  363. // Add the object to the player's inventory
  364. inventory.Add(hit.collider.gameObject);
  365. // Remove the object from the scene
  366. hit.collider.gameObject.SetActive(false);
  367. }
  368. }
  369. }
  370.  
  371. // Check if player is holding an item and presses pickup key again to drop it
  372. if (Input.GetKeyDown(pickupKey) && itemHeld != null)
  373. {
  374. // Drop the item
  375. itemHeld.SetActive(true);
  376. itemHeld.transform.position = transform.position + transform.forward * 1.5f;
  377. itemHeld = null;
  378. }
  379.  
  380. // Check if player presses number keys to select items in inventory
  381. for (int i = 0; i < inventory.Count; i++)
  382. {
  383. if (Input.GetKeyDown((i + 1).ToString()))
  384. {
  385. // Drop any item that is currently being held
  386. if (itemHeld != null)
  387. {
  388. itemHeld.SetActive(true);
  389. itemHeld.transform.position = transform.position + transform.forward * 1.5f;
  390. }
  391.  
  392. // Select the item in inventory and remove it from inventory list
  393. itemHeld = inventory[i];
  394. inventory.RemoveAt(i);
  395. break;
  396. }
  397. }
  398. }
  399. }
  400.  
  401.  
  402. I added a ignoreLayer variable of type LayerMask that allows you to specify which layers should be ignored by the Physics.Raycast function. In this case, the ~ignoreLayer syntax in the Physics.Raycast call means that any objects on the ignoreLayer will be ignored.
  403.  
  404. Make sure to assign a valid layer mask to the ignoreLayer variable in the Inspector.
  405. --------------------------
  406. I think this inventory system is too complicated. Let's not use this script. Instead, give me a script to interact with objects in the scene. By interating with an object I want to get ressources out of it : wood or stones.
  407. --------------------------
  408. Sure, here's a script that allows the player to interact with objects in the scene to gather resources (wood or stones):
  409.  
  410. csharp
  411. Copy code
  412. using UnityEngine;
  413.  
  414. public class ResourceGatherer : MonoBehaviour
  415. {
  416. public float maxInteractDistance = 2f;
  417. public KeyCode interactKey = KeyCode.E;
  418.  
  419. void Update()
  420. {
  421. // Check if player presses interact key
  422. if (Input.GetKeyDown(interactKey))
  423. {
  424. // Check if there's an object in front of the player that can be interacted with
  425. RaycastHit hit;
  426. if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance))
  427. {
  428. // Check if the object has a "Resource" tag
  429. if (hit.collider.CompareTag("Resource"))
  430. {
  431. // Get the resource type from the object's Resource component
  432. Resource resource = hit.collider.gameObject.GetComponent<Resource>();
  433.  
  434. // Gather the resource
  435. int amountGathered = resource.Gather();
  436.  
  437. // Add the resource to the player's inventory
  438. if (resource.resourceType == Resource.ResourceType.Wood)
  439. {
  440. Debug.Log("Gathered " + amountGathered + " wood.");
  441. // TODO: Add wood to player's inventory
  442. }
  443. else if (resource.resourceType == Resource.ResourceType.Stone)
  444. {
  445. Debug.Log("Gathered " + amountGathered + " stone.");
  446. // TODO: Add stone to player's inventory
  447. }
  448. }
  449. }
  450. }
  451. }
  452. }
  453.  
  454.  
  455. This script uses a similar Raycast system to detect objects in front of the player that can be interacted with. If the object has a Resource component with a valid resourceType, the player will be able to gather resources from it by calling the Gather function of the Resource component.
  456.  
  457. This script doesn't use an inventory system, but you could easily modify it to keep track of how much wood or stone the player has gathered and display it in a UI element.
  458. --------------------------
  459. Could you give me the script "Ressource" associated with this script ?
  460. --------------------------
  461. Sure, here's a sample Resource script that you could use:
  462.  
  463. csharp
  464. Copy code
  465. using UnityEngine;
  466.  
  467. public class Resource : MonoBehaviour
  468. {
  469. public enum ResourceType
  470. {
  471. Wood,
  472. Stone
  473. }
  474.  
  475. public ResourceType resourceType;
  476. public int maxAmount = 10;
  477. public int amountLeft = 10;
  478.  
  479. public int Gather()
  480. {
  481. int amountGathered = Mathf.Min(1, amountLeft); // Gather 1 unit or less if there's not enough left
  482. amountLeft -= amountGathered;
  483.  
  484. if (amountLeft <= 0)
  485. {
  486. Destroy(gameObject);
  487. }
  488.  
  489. return amountGathered;
  490. }
  491. }
  492.  
  493.  
  494. This script defines a Resource component that can be attached to any game object in the scene that should contain resources that can be gathered by the player. The Resource component has a resourceType field to specify whether the resource is wood or stone, and a maxAmount field to specify how much of the resource is available in the object.
  495.  
  496. When the player interacts with the object, the Gather function is called to collect a unit of the resource. This function decrements the amountLeft field and destroys the object if there's no more resource left. It also returns the amount of resource gathered, which is then used by the ResourceGatherer script to add the resource to the player's inventory.
  497. --------------------------
  498. We need to add a layermask system in ResourceGatherer to ignore certains objects that could get in the way
  499. --------------------------
  500. Sure, here's the updated ResourceGatherer script with a layer mask system:
  501.  
  502. csharp
  503. Copy code
  504. using UnityEngine;
  505.  
  506. public class ResourceGatherer : MonoBehaviour
  507. {
  508. public float maxInteractDistance = 2f;
  509. public KeyCode interactKey = KeyCode.E;
  510. public LayerMask interactLayerMask;
  511.  
  512. void Update()
  513. {
  514. // Check if player presses interact key
  515. if (Input.GetKeyDown(interactKey))
  516. {
  517. // Check if there's an object in front of the player that can be interacted with
  518. RaycastHit hit;
  519. if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance, interactLayerMask))
  520. {
  521. // Check if the object has a "Resource" tag
  522. if (hit.collider.CompareTag("Resource"))
  523. {
  524. // Get the resource type from the object's Resource component
  525. Resource resource = hit.collider.gameObject.GetComponent<Resource>();
  526.  
  527. // Gather the resource
  528. int amountGathered = resource.Gather();
  529.  
  530. // Add the resource to the player's inventory
  531. if (resource.resourceType == Resource.ResourceType.Wood)
  532. {
  533. Debug.Log("Gathered " + amountGathered + " wood.");
  534. // TODO: Add wood to player's inventory
  535. }
  536. else if (resource.resourceType == Resource.ResourceType.Stone)
  537. {
  538. Debug.Log("Gathered " + amountGathered + " stone.");
  539. // TODO: Add stone to player's inventory
  540. }
  541. }
  542. }
  543. }
  544. }
  545. }
  546.  
  547.  
  548. This script now has a LayerMask field called interactLayerMask. When the player interacts with an object, the Physics.Raycast function is called with this mask to ignore certain layers that could get in the way (like the player's own collider). To set the interact layer mask, you can simply assign the appropriate layers in the inspector.
  549.  
  550. If you want to ignore multiple layers, you can use the | operator to combine them. For example, to ignore both the player's and the environment's layers, you could set the interactLayerMask to ~(1 << LayerMask.NameToLayer("Player") | 1 << LayerMask.NameToLayer("Environment")).
  551. --------------------------
  552. How could I store how many woods and stones I have in the script "ResourceGatherer" ?
  553. --------------------------
  554. One way to store the player's inventory of resources is to use a dictionary that maps resource types to the number of units the player has collected. Here's an updated version of the ResourceGatherer script that includes an inventory dictionary:
  555.  
  556. csharp
  557. Copy code
  558. using System.Collections.Generic;
  559. using UnityEngine;
  560.  
  561. public class ResourceGatherer : MonoBehaviour
  562. {
  563. public float maxInteractDistance = 2f;
  564. public KeyCode interactKey = KeyCode.E;
  565. public LayerMask interactLayerMask;
  566.  
  567. private Dictionary<Resource.ResourceType, int> inventory = new Dictionary<Resource.ResourceType, int>();
  568.  
  569. private void Start()
  570. {
  571. // Initialize the inventory with 0 units of each resource type
  572. inventory[Resource.ResourceType.Wood] = 0;
  573. inventory[Resource.ResourceType.Stone] = 0;
  574. }
  575.  
  576. void Update()
  577. {
  578. // Check if player presses interact key
  579. if (Input.GetKeyDown(interactKey))
  580. {
  581. // Check if there's an object in front of the player that can be interacted with
  582. RaycastHit hit;
  583. if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance, interactLayerMask))
  584. {
  585. // Check if the object has a "Resource" tag
  586. if (hit.collider.CompareTag("Resource"))
  587. {
  588. // Get the resource type from the object's Resource component
  589. Resource resource = hit.collider.gameObject.GetComponent<Resource>();
  590.  
  591. // Gather the resource
  592. int amountGathered = resource.Gather();
  593.  
  594. // Add the resource to the player's inventory
  595. if (resource.resourceType == Resource.ResourceType.Wood)
  596. {
  597. Debug.Log("Gathered " + amountGathered + " wood.");
  598. inventory[Resource.ResourceType.Wood] += amountGathered;
  599. }
  600. else if (resource.resourceType == Resource.ResourceType.Stone)
  601. {
  602. Debug.Log("Gathered " + amountGathered + " stone.");
  603. inventory[Resource.ResourceType.Stone] += amountGathered;
  604. }
  605. }
  606. }
  607. }
  608. }
  609. }
  610.  
  611.  
  612. This script initializes a dictionary called inventory in the Start method. The dictionary maps ResourceType values to integers representing the number of units the player has collected. When the player collects a resource, the appropriate value in the dictionary is incremented by the amount gathered. You can access the number of units the player has collected for a particular resource type using the dictionary's [] operator. For example, to get the number of wood units the player has collected, you can use inventory[Resource.ResourceType.Wood].
  613. --------------------------
  614. is there a way to display the inventory content in the inspector ?
  615. --------------------------
  616. Yes, you can display the contents of the inventory dictionary in the Unity inspector by using the [SerializeField] attribute on a private variable that holds the inventory data. Here's an updated version of the ResourceGatherer script that includes a private variable called inventoryData that can be viewed in the inspector:
  617.  
  618. csharp
  619. Copy code
  620. using System.Collections.Generic;
  621. using UnityEngine;
  622.  
  623. public class ResourceGatherer : MonoBehaviour
  624. {
  625. public float maxInteractDistance = 2f;
  626. public KeyCode interactKey = KeyCode.E;
  627. public LayerMask interactLayerMask;
  628.  
  629. [SerializeField]
  630. private InventoryData inventoryData;
  631.  
  632. private Dictionary<Resource.ResourceType, int> inventory;
  633.  
  634. private void Awake()
  635. {
  636. inventory = inventoryData.inventory;
  637. }
  638.  
  639. void Update()
  640. {
  641. // Check if player presses interact key
  642. if (Input.GetKeyDown(interactKey))
  643. {
  644. // Check if there's an object in front of the player that can be interacted with
  645. RaycastHit hit;
  646. if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance, interactLayerMask))
  647. {
  648. // Check if the object has a "Resource" tag
  649. if (hit.collider.CompareTag("Resource"))
  650. {
  651. // Get the resource type from the object's Resource component
  652. Resource resource = hit.collider.gameObject.GetComponent<Resource>();
  653.  
  654. // Gather the resource
  655. int amountGathered = resource.Gather();
  656.  
  657. // Add the resource to the player's inventory
  658. if (resource.resourceType == Resource.ResourceType.Wood)
  659. {
  660. Debug.Log("Gathered " + amountGathered + " wood.");
  661. inventory[Resource.ResourceType.Wood] += amountGathered;
  662. }
  663. else if (resource.resourceType == Resource.ResourceType.Stone)
  664. {
  665. Debug.Log("Gathered " + amountGathered + " stone.");
  666. inventory[Resource.ResourceType.Stone] += amountGathered;
  667. }
  668. }
  669. }
  670. }
  671. }
  672. }
  673.  
  674. [System.Serializable]
  675. public class InventoryData
  676. {
  677. public Dictionary<Resource.ResourceType, int> inventory = new Dictionary<Resource.ResourceType, int>
  678. {
  679. { Resource.ResourceType.Wood, 0 },
  680. { Resource.ResourceType.Stone, 0 }
  681. };
  682. }
  683.  
  684.  
  685. In this version of the script, the inventory dictionary is stored in a separate InventoryData class. The InventoryData class is marked with the [System.Serializable] attribute so that it can be viewed in the inspector. The inventory dictionary is initialized with default values for each resource type in the InventoryData constructor.
  686.  
  687. In the ResourceGatherer script, a private variable called inventoryData is defined with the [SerializeField] attribute. This allows the inventoryData variable to be viewed in the inspector. In the Awake method, the inventory dictionary is set to the value of inventoryData.inventory. Any changes made to the inventory dictionary in the game will be reflected in the inspector when the game is paused or stopped.
  688. --------------------------
  689. I'm now using this proposition, the previous one was good enough. How can I display the current player's ressources on screen ?
  690. --------------------------
  691. To display the player's resources on screen, you can create a UI text element and use the Text component to display the current values of the player's resources.
  692.  
  693. Here's an updated version of the ResourceGatherer script that includes a private Text variable for displaying the player's resources on screen:
  694.  
  695. csharp
  696. Copy code
  697. using System.Collections.Generic;
  698. using UnityEngine;
  699. using UnityEngine.UI;
  700.  
  701. public class ResourceGatherer : MonoBehaviour
  702. {
  703. public float maxInteractDistance = 2f;
  704. public KeyCode interactKey = KeyCode.E;
  705. public LayerMask interactLayerMask;
  706.  
  707. [SerializeField]
  708. private Text inventoryText;
  709.  
  710. private Dictionary<Resource.ResourceType, int> inventory;
  711.  
  712. private void Awake()
  713. {
  714. inventory = new Dictionary<Resource.ResourceType, int>
  715. {
  716. { Resource.ResourceType.Wood, 0 },
  717. { Resource.ResourceType.Stone, 0 }
  718. };
  719. }
  720.  
  721. void Update()
  722. {
  723. // Check if player presses interact key
  724. if (Input.GetKeyDown(interactKey))
  725. {
  726. // Check if there's an object in front of the player that can be interacted with
  727. RaycastHit hit;
  728. if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance, interactLayerMask))
  729. {
  730. // Check if the object has a "Resource" tag
  731. if (hit.collider.CompareTag("Resource"))
  732. {
  733. // Get the resource type from the object's Resource component
  734. Resource resource = hit.collider.gameObject.GetComponent<Resource>();
  735.  
  736. // Gather the resource
  737. int amountGathered = resource.Gather();
  738.  
  739. // Add the resource to the player's inventory
  740. if (resource.resourceType == Resource.ResourceType.Wood)
  741. {
  742. Debug.Log("Gathered " + amountGathered + " wood.");
  743. inventory[Resource.ResourceType.Wood] += amountGathered;
  744. }
  745. else if (resource.resourceType == Resource.ResourceType.Stone)
  746. {
  747. Debug.Log("Gathered " + amountGathered + " stone.");
  748. inventory[Resource.ResourceType.Stone] += amountGathered;
  749. }
  750.  
  751. // Update the inventory text
  752. UpdateInventoryText();
  753. }
  754. }
  755. }
  756. }
  757.  
  758. private void UpdateInventoryText()
  759. {
  760. // Build a string with the current inventory contents
  761. string inventoryString = "Inventory:\n";
  762. inventoryString += "Wood: " + inventory[Resource.ResourceType.Wood] + "\n";
  763. inventoryString += "Stone: " + inventory[Resource.ResourceType.Stone];
  764.  
  765. // Update the text component
  766. inventoryText.text = inventoryString;
  767. }
  768. }
  769.  
  770.  
  771. In this version of the script, a private Text variable called inventoryText is defined with the [SerializeField] attribute. This allows the inventoryText variable to be set in the inspector.
  772.  
  773. In the Update method, the `Update
  774. --------------------------
  775. Great, I now need a script with which the player can interact if the inventory contains 2 woods and 2 stones
  776. --------------------------
  777. Sure, here's an example script that checks the player's inventory and allows interaction if it contains 2 woods and 2 stones:
  778.  
  779. csharp
  780. Copy code
  781. using UnityEngine;
  782.  
  783. public class InteractionChecker : MonoBehaviour
  784. {
  785. public ResourceGatherer resourceGatherer;
  786. public GameObject interactableObject;
  787. public KeyCode interactKey = KeyCode.E;
  788.  
  789. private bool hasInteracted = false;
  790.  
  791. void Update()
  792. {
  793. if (!hasInteracted)
  794. {
  795. // Check if the player has 2 woods and 2 stones in their inventory
  796. if (resourceGatherer.GetResourceCount(Resource.ResourceType.Wood) >= 2
  797. && resourceGatherer.GetResourceCount(Resource.ResourceType.Stone) >= 2)
  798. {
  799. // Display a message to the player to interact with the object
  800. Debug.Log("You can interact with the object now.");
  801.  
  802. // Check if the player presses the interact key
  803. if (Input.GetKeyDown(interactKey))
  804. {
  805. // Interact with the object
  806. Debug.Log("Interacting with the object...");
  807. interactableObject.GetComponent<Interactable>().Interact();
  808.  
  809. // Remove 2 woods and 2 stones from the player's inventory
  810. resourceGatherer.RemoveResource(Resource.ResourceType.Wood, 2);
  811. resourceGatherer.RemoveResource(Resource.ResourceType.Stone, 2);
  812.  
  813. // Set the hasInteracted flag to true to prevent further interactions
  814. hasInteracted = true;
  815. }
  816. }
  817. }
  818. }
  819. }
  820.  
  821.  
  822. In this script, a ResourceGatherer variable called resourceGatherer is defined to reference the player's inventory. A GameObject variable called interactableObject is defined to reference the object that the player can interact with if they have 2 woods and 2 stones in their inventory.
  823.  
  824. In the Update method, the script checks if the player has not yet interacted and if they have 2 woods and 2 stones in their inventory. If so, it displays a message to the player to interact with the object and checks if the interact key is pressed. If the key is pressed, it calls the Interact method on the Interactable component of the interactableObject, removes 2 woods and 2 stones from the player's inventory using the RemoveResource method of the resourceGatherer, and sets the hasInteracted flag to true to prevent further interactions.
  825. --------------------------
  826. The methods "GetResourceCount" and "RemoveResource" does not exist in ResourceGatherer, could you make them ?
  827. --------------------------
  828. Sure, here's an updated version of the ResourceGatherer script with the GetResourceCount and RemoveResource methods implemented:
  829.  
  830. csharp
  831. Copy code
  832. using System.Collections.Generic;
  833. using UnityEngine;
  834.  
  835. public class ResourceGatherer : MonoBehaviour
  836. {
  837. // Define a dictionary to store the player's resources
  838. private Dictionary<Resource.ResourceType, int> resources = new Dictionary<Resource.ResourceType, int>();
  839.  
  840. void Start()
  841. {
  842. // Initialize the dictionary with all resource types and a count of 0 for each
  843. foreach (Resource.ResourceType resourceType in System.Enum.GetValues(typeof(Resource.ResourceType)))
  844. {
  845. resources[resourceType] = 0;
  846. }
  847. }
  848.  
  849. // Add a given amount of a given resource to the player's inventory
  850. public void AddResource(Resource.ResourceType resourceType, int amount)
  851. {
  852. resources[resourceType] += amount;
  853. }
  854.  
  855. // Get the current count of a given resource in the player's inventory
  856. public int GetResourceCount(Resource.ResourceType resourceType)
  857. {
  858. return resources[resourceType];
  859. }
  860.  
  861. // Remove a given amount of a given resource from the player's inventory
  862. public void RemoveResource(Resource.ResourceType resourceType, int amount)
  863. {
  864. resources[resourceType] -= amount;
  865.  
  866. // Make sure the resource count doesn't go below 0
  867. if (resources[resourceType] < 0)
  868. {
  869. resources[resourceType] = 0;
  870. }
  871. }
  872. }
  873.  
  874.  
  875. In this updated version of the ResourceGatherer script, the resources variable is defined as a dictionary with Resource.ResourceType keys and int values to store the player's resources.
  876.  
  877. The Start method initializes the dictionary with all resource types and a count of
  878. --------------------------
  879. In the script InteractionChecker, please replace the line "interactableObject.GetComponent<Interactable>().Interact();" by a line enabling a gameobject instead
  880. --------------------------
  881. Sure! Here's an updated version of the InteractionChecker script with the requested change:
  882.  
  883. csharp
  884. Copy code
  885. using UnityEngine;
  886.  
  887. public class InteractionChecker : MonoBehaviour
  888. {
  889. public float interactionDistance = 2f;
  890. public LayerMask interactableLayer;
  891.  
  892. private Camera mainCamera;
  893.  
  894. void Start()
  895. {
  896. mainCamera = Camera.main;
  897. }
  898.  
  899. void Update()
  900. {
  901. if (Input.GetKeyDown(KeyCode.E))
  902. {
  903. RaycastHit hit;
  904. if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, interactionDistance, interactableLayer))
  905. {
  906. GameObject interactableObject = hit.collider.gameObject;
  907.  
  908. // Enable the gameobject instead of calling Interact method
  909. interactableObject.SetActive(true);
  910. }
  911. }
  912. }
  913. }
  914.  
  915.  
  916. In this updated version of the InteractionChecker script, I replaced the line interactableObject.GetComponent<Interactable>().Interact(); with interactableObject.SetActive(true);. This line enables the gameobject instead of calling the Interact method of the Interactable component.
  917.  
  918. With this change, when the player presses the "E" key while looking at an interactable object, the object will be enabled instead of calling its Interact method.
  919. --------------------------
  920. the object to enable should be stored in a variable
  921. --------------------------
  922. Sure! Here's an updated version of the InteractionChecker script that stores the interactable object in a variable before enabling it:
  923.  
  924. csharp
  925. Copy code
  926. using UnityEngine;
  927.  
  928. public class InteractionChecker : MonoBehaviour
  929. {
  930. public float interactionDistance = 2f;
  931. public LayerMask interactableLayer;
  932.  
  933. private Camera mainCamera;
  934. private GameObject interactableObject;
  935.  
  936. void Start()
  937. {
  938. mainCamera = Camera.main;
  939. }
  940.  
  941. void Update()
  942. {
  943. if (Input.GetKeyDown(KeyCode.E))
  944. {
  945. RaycastHit hit;
  946. if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, interactionDistance, interactableLayer))
  947. {
  948. interactableObject = hit.collider.gameObject;
  949. // Disable collider to prevent further interactions
  950. interactableObject.GetComponent<Collider>().enabled = false;
  951. // Enable the gameobject instead of calling Interact method
  952. interactableObject.SetActive(true);
  953. }
  954. }
  955. }
  956. }
  957.  
  958.  
  959. In this updated version of the script, I added a new private field interactableObject that stores the current interactable object. When the player presses the "E" key, the script sets the interactableObject variable to the object that was hit by the raycast.
  960.  
  961. Then, before enabling the object, I disabled its collider to prevent further interactions. Finally, I enabled the gameobject as before with interactableObject.SetActive(true);.
  962. --------------------------
  963. Let's forget this InteractionChecker script. I need the player to be able to interact with an object. If the player has 2 woods and 2 stones we destroy this object and we set active another one.
  964. --------------------------
  965. Sure! Here's an example script that should accomplish what you're looking for:
  966.  
  967. csharp
  968. Copy code
  969. using UnityEngine;
  970.  
  971. public class ObjectInteractor : MonoBehaviour
  972. {
  973. public GameObject replacementObject;
  974. public int requiredWood = 2;
  975. public int requiredStone = 2;
  976.  
  977. private ResourceGatherer resourceGatherer;
  978.  
  979. void Start()
  980. {
  981. resourceGatherer = GetComponent<ResourceGatherer>();
  982. }
  983.  
  984. void OnTriggerEnter(Collider other)
  985. {
  986. if (CheckRequirements() && other.CompareTag("Interactable"))
  987. {
  988. // Destroy the current object and activate the replacement object
  989. Destroy(other.gameObject);
  990. replacementObject.SetActive(true);
  991.  
  992. // Remove the required resources from the inventory
  993. resourceGatherer.RemoveResource("Wood", requiredWood);
  994. resourceGatherer.RemoveResource("Stone", requiredStone);
  995. }
  996. }
  997.  
  998. bool CheckRequirements()
  999. {
  1000. int woodCount = resourceGatherer.GetResourceCount("Wood");
  1001. int stoneCount = resourceGatherer.GetResourceCount("Stone");
  1002. return woodCount >= requiredWood && stoneCount >= requiredStone;
  1003. }
  1004. }
  1005.  
  1006.  
  1007. In this script, we're checking the player's inventory when they collide with an object tagged as "Interactable". If the player has enough wood and stone, we destroy the current object and activate the replacement object.
  1008.  
  1009. To accomplish this, we're using the CheckRequirements method to check the player's inventory against the required resources. If the requirements are met, we destroy the current object with Destroy(other.gameObject);, activate the replacement object with replacementObject.SetActive(true);, and remove the required resources from the player's inventory with resourceGatherer.RemoveResource("Wood", requiredWood); and resourceGatherer.RemoveResource("Stone", requiredStone);.
  1010. --------------------------
  1011. Not bad but I'd like the player to interact by pressing a key not by using OnTriggerEnter
  1012. --------------------------
  1013. Alright, in that case, we can modify the script to use the input system to detect when the player wants to interact with an object. Here's an updated script that uses a key press to interact:
  1014.  
  1015. csharp
  1016. Copy code
  1017. using UnityEngine;
  1018. using UnityEngine.InputSystem;
  1019.  
  1020. public class ObjectInteractor : MonoBehaviour
  1021. {
  1022. public GameObject replacementObject;
  1023. public int requiredWood = 2;
  1024. public int requiredStone = 2;
  1025. public KeyCode interactKey = KeyCode.E;
  1026.  
  1027. private ResourceGatherer resourceGatherer;
  1028. private Collider currentObject;
  1029.  
  1030. void Start()
  1031. {
  1032. resourceGatherer = GetComponent<ResourceGatherer>();
  1033. }
  1034.  
  1035. void Update()
  1036. {
  1037. if (currentObject != null && Keyboard.current[interactKey].wasPressedThisFrame)
  1038. {
  1039. if (CheckRequirements())
  1040. {
  1041. // Destroy the current object and activate the replacement object
  1042. Destroy(currentObject.gameObject);
  1043. replacementObject.SetActive(true);
  1044.  
  1045. // Remove the required resources from the inventory
  1046. resourceGatherer.RemoveResource("Wood", requiredWood);
  1047. resourceGatherer.RemoveResource("Stone", requiredStone);
  1048.  
  1049. currentObject = null;
  1050. }
  1051. }
  1052. }
  1053.  
  1054. void OnTriggerEnter(Collider other)
  1055. {
  1056. if (other.CompareTag("Interactable"))
  1057. {
  1058. currentObject = other;
  1059. }
  1060. }
  1061.  
  1062. void OnTriggerExit(Collider other)
  1063. {
  1064. if (other == currentObject)
  1065. {
  1066. currentObject = null;
  1067. }
  1068. }
  1069.  
  1070. bool CheckRequirements()
  1071. {
  1072. int woodCount = resourceGatherer.GetResourceCount("Wood");
  1073. int stoneCount = resourceGatherer.GetResourceCount("Stone");
  1074. return woodCount >= requiredWood && stoneCount >= requiredStone;
  1075. }
  1076. }
  1077.  
  1078.  
  1079. In this updated script, we're using the Update method to detect if the player has pressed the interact key (interactKey). If they have, and the player meets the requirements to interact with the object, we destroy the current object, activate the replacement object, and remove the required resources from the player's inventory.
  1080.  
  1081. We're also using the OnTriggerEnter and OnTriggerExit methods to keep track of the current object that the player is able to interact with.
  1082. --------------------------
  1083. This script is not what we want. Let's try another way.
  1084. The player should be able to interact with an object by pressing a Key on the keyboard. If the player has 2 woods and 2 stones, we get the objet's child and enable it.
  1085. --------------------------
  1086. Sure, here's a script that should accomplish that:
  1087.  
  1088. csharp
  1089. Copy code
  1090. using UnityEngine;
  1091.  
  1092. public class InteractWithObject : MonoBehaviour
  1093. {
  1094. public KeyCode interactKey = KeyCode.E;
  1095. public int woodNeeded = 2;
  1096. public int stoneNeeded = 2;
  1097. public GameObject objectToDisable;
  1098. public GameObject objectToEnable;
  1099.  
  1100. private ResourceGatherer resourceGatherer;
  1101.  
  1102. private void Start()
  1103. {
  1104. resourceGatherer = GetComponent<ResourceGatherer>();
  1105. }
  1106.  
  1107. private void Update()
  1108. {
  1109. if (Input.GetKeyDown(interactKey))
  1110. {
  1111. if (resourceGatherer.GetResourceCount(ResourceType.Wood) >= woodNeeded && resourceGatherer.GetResourceCount(ResourceType.Stone) >= stoneNeeded)
  1112. {
  1113. resourceGatherer.RemoveResource(ResourceType.Wood, woodNeeded);
  1114. resourceGatherer.RemoveResource(ResourceType.Stone, stoneNeeded);
  1115. objectToDisable.SetActive(false);
  1116. objectToEnable.transform.GetChild(0).gameObject.SetActive(true);
  1117. }
  1118. }
  1119. }
  1120. }
  1121.  
  1122.  
  1123. This script checks for a key press and then checks if the player has enough wood and stone to interact with the object. If the player has enough resources, the script removes the resources from the player's inventory and disables the original object while enabling the child of the new object. The objectToDisable and objectToEnable variables are assigned in the inspector to the original and new objects, respectively.
  1124. --------------------------
  1125. This should work but I want the player to look at the object to disable AND press the interact key
  1126. --------------------------
  1127. Sure, here's an updated script that requires the player to look at the object and press the interact key:
  1128.  
  1129. csharp
  1130. Copy code
  1131. using UnityEngine;
  1132.  
  1133. public class InteractWithObject : MonoBehaviour
  1134. {
  1135. public KeyCode interactKey = KeyCode.E;
  1136. public int woodNeeded = 2;
  1137. public int stoneNeeded = 2;
  1138. public GameObject objectToDisable;
  1139. public GameObject objectToEnable;
  1140. public float interactionRange = 3f;
  1141.  
  1142. private ResourceGatherer resourceGatherer;
  1143.  
  1144. private void Start()
  1145. {
  1146. resourceGatherer = GetComponent<ResourceGatherer>();
  1147. }
  1148.  
  1149. private void Update()
  1150. {
  1151. if (Input.GetKeyDown(interactKey))
  1152. {
  1153. RaycastHit hit;
  1154. if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, interactionRange))
  1155. {
  1156. if (hit.collider.gameObject == objectToDisable && resourceGatherer.GetResourceCount(ResourceType.Wood) >= woodNeeded && resourceGatherer.GetResourceCount(ResourceType.Stone) >= stoneNeeded)
  1157. {
  1158. resourceGatherer.RemoveResource(ResourceType.Wood, woodNeeded);
  1159. resourceGatherer.RemoveResource(ResourceType.Stone, stoneNeeded);
  1160. objectToDisable.SetActive(false);
  1161. objectToEnable.transform.GetChild(0).gameObject.SetActive(true);
  1162. }
  1163. }
  1164. }
  1165. }
  1166. }
  1167.  
  1168.  
  1169. This script uses a Raycast to check if the player is looking at the object to disable, within the interactionRange specified in the inspector. If the player is looking at the object and has enough resources, then the object is disabled and the new object is enabled, as before.
  1170. --------------------------
  1171. Remember the script ResourceGatherer ? I'd like to display a text on screen when the player looks at an object with the tag "Resource"
  1172. --------------------------
  1173. Sure! You can add the following script to the player camera and attach a UI Text object to it:
  1174.  
  1175. csharp
  1176. Copy code
  1177. using UnityEngine;
  1178. using UnityEngine.UI;
  1179.  
  1180. public class ResourceText : MonoBehaviour
  1181. {
  1182. public float maxDistance = 5f; // Maximum distance to detect resources
  1183. public LayerMask layerMask; // Layer mask to detect resources
  1184. public Text textObject; // UI text object to display the message
  1185.  
  1186. private void Update()
  1187. {
  1188. // Cast a ray from the center of the screen
  1189. Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
  1190. RaycastHit hit;
  1191. if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
  1192. {
  1193. // If the ray hits a resource object, display the message
  1194. if (hit.collider.CompareTag("Resource"))
  1195. {
  1196. textObject.text = "Press E to gather resources";
  1197. textObject.gameObject.SetActive(true);
  1198. }
  1199. else
  1200. {
  1201. textObject.gameObject.SetActive(false);
  1202. }
  1203. }
  1204. else
  1205. {
  1206. textObject.gameObject.SetActive(false);
  1207. }
  1208. }
  1209. }
  1210.  
  1211.  
  1212. This script casts a ray from the center of the screen and detects any resource object within a certain distance. If a resource object is detected, it displays the message on the UI text object.
  1213. --------------------------
  1214. In the script InteractWithObject, if the player does not have enough ressources we need to display a text on screen to tell the player he needs more ressources
  1215. --------------------------
  1216. To display a text on screen when the player doesn't have enough resources, we can add a UI element to the canvas and set it to be initially disabled. Then, in the Interact() function of the InteractWithObject script, we can check if the player has enough resources. If not, we enable the UI element with the error message.
  1217.  
  1218. Here's the updated code:
  1219.  
  1220. C#
  1221. Copy code
  1222. using System.Collections;
  1223. using System.Collections.Generic;
  1224. using UnityEngine;
  1225.  
  1226. public class InteractWithObject : MonoBehaviour
  1227. {
  1228. public KeyCode interactKey = KeyCode.E;
  1229. public int woodNeeded = 2;
  1230. public int stoneNeeded = 2;
  1231. public GameObject objectToDisable;
  1232. public GameObject objectToEnable;
  1233. public GameObject notEnoughResourcesText;
  1234.  
  1235. private ResourceGatherer resourceGatherer;
  1236.  
  1237. private void Start()
  1238. {
  1239. resourceGatherer = GetComponent<ResourceGatherer>();
  1240. }
  1241.  
  1242. private void Update()
  1243. {
  1244. if (Input.GetKeyDown(interactKey))
  1245. {
  1246. RaycastHit hit;
  1247. if (Physics.Raycast(transform.position, transform.forward, out hit, 3f))
  1248. {
  1249. if (hit.transform.CompareTag("Resource"))
  1250. {
  1251. if (resourceGatherer.GetResourceCount(ResourceType.Wood) >= woodNeeded
  1252. && resourceGatherer.GetResourceCount(ResourceType.Stone) >= stoneNeeded)
  1253. {
  1254. resourceGatherer.RemoveResource(ResourceType.Wood, woodNeeded);
  1255. resourceGatherer.RemoveResource(ResourceType.Stone, stoneNeeded);
  1256. objectToDisable.SetActive(false);
  1257. objectToEnable.SetActive(true);
  1258. }
  1259. else
  1260. {
  1261. notEnoughResourcesText.SetActive(true);
  1262. StartCoroutine(HideText());
  1263. }
  1264. }
  1265. }
  1266. }
  1267. }
  1268.  
  1269. private IEnumerator HideText()
  1270. {
  1271. yield return new WaitForSeconds(2f);
  1272. notEnoughResourcesText.SetActive(false);
  1273. }
  1274. }
  1275.  
  1276.  
  1277. In this updated code, we added a public GameObject variable called notEnoughResourcesText that refers to the UI element that will display the error message. We also added a new Coroutine called HideText() that will hide the error message after 2 seconds.
  1278.  
  1279. In the Update() function, we check if the player has pressed the interact key and if the player is looking at an object with the "Resource" tag. If the player has enough resources, we remove them from the inventory and enable the object to be enabled while disabling the object to be disabled. If the player does not have enough resources, we enable the UI element with the error message and start the HideText() coroutine to hide it after 2 seconds.
  1280. --------------------------
  1281. In this same script, when calling "objectToEnable.SetActive(true);" we should also display a text on screen indicating to the player that he won
  1282. --------------------------
  1283. Sure, here's an updated version of the InteractWithObject script that includes the text display when the player wins:
  1284.  
  1285. csharp
  1286. Copy code
  1287. using UnityEngine;
  1288. using UnityEngine.UI;
  1289.  
  1290. public class InteractWithObject : MonoBehaviour
  1291. {
  1292. public KeyCode interactKey = KeyCode.E;
  1293. public int requiredWood = 2;
  1294. public int requiredStone = 2;
  1295. public GameObject objectToDisable;
  1296. public GameObject objectToEnable;
  1297. public Text messageText;
  1298.  
  1299. private ResourceGatherer resourceGatherer;
  1300.  
  1301. private void Start()
  1302. {
  1303. resourceGatherer = GetComponent<ResourceGatherer>();
  1304. }
  1305.  
  1306. private void Update()
  1307. {
  1308. if (Input.GetKeyDown(interactKey))
  1309. {
  1310. RaycastHit hit;
  1311. if (Physics.Raycast(transform.position, transform.forward, out hit, 3f))
  1312. {
  1313. if (hit.transform.CompareTag("Resource"))
  1314. {
  1315. int woodCount = resourceGatherer.GetResourceCount(ResourceType.Wood);
  1316. int stoneCount = resourceGatherer.GetResourceCount(ResourceType.Stone);
  1317.  
  1318. if (woodCount >= requiredWood && stoneCount >= requiredStone)
  1319. {
  1320. resourceGatherer.RemoveResource(ResourceType.Wood, requiredWood);
  1321. resourceGatherer.RemoveResource(ResourceType.Stone, requiredStone);
  1322. objectToDisable.SetActive(false);
  1323. objectToEnable.SetActive(true);
  1324. messageText.text = "You won!";
  1325. }
  1326. else
  1327. {
  1328. messageText.text = "You need more resources.";
  1329. }
  1330. }
  1331. }
  1332. }
  1333. }
  1334. }
  1335.  
  1336.  
  1337. Note that I added a messageText variable of type Text to the script, which you can assign in the inspector to a Text object in your scene. When the player wins, the text will be set to "You won!", and when they don't have enough resources, it will be set to "You need more resources."
  1338. --------------------------
  1339. In this same script, we should start a timer when the game starts and stop it when the player won, then we can display how much time it took him to complete the game
  1340. --------------------------
  1341. Sure, here's an updated version of the InteractWithObject script with a timer:
  1342.  
  1343. csharp
  1344. Copy code
  1345. using UnityEngine;
  1346. using UnityEngine.UI;
  1347.  
  1348. public class InteractWithObject : MonoBehaviour
  1349. {
  1350. public KeyCode interactKey = KeyCode.E;
  1351. public LayerMask interactableMask;
  1352. public Text hintText;
  1353. public Text winText;
  1354.  
  1355. public int woodNeeded = 2;
  1356. public int stoneNeeded = 2;
  1357. public GameObject objectToDisable;
  1358. public GameObject objectToEnable;
  1359.  
  1360. private int woodCount = 0;
  1361. private int stoneCount = 0;
  1362. private bool canInteract = false;
  1363. private bool hasWon = false;
  1364. private float startTime;
  1365.  
  1366. private void Start()
  1367. {
  1368. startTime = Time.time;
  1369. }
  1370.  
  1371. private void Update()
  1372. {
  1373. if (canInteract && !hasWon && Input.GetKeyDown(interactKey))
  1374. {
  1375. if (woodCount >= woodNeeded && stoneCount >= stoneNeeded)
  1376. {
  1377. objectToDisable.SetActive(false);
  1378. objectToEnable.SetActive(true);
  1379. hintText.gameObject.SetActive(false);
  1380. winText.gameObject.SetActive(true);
  1381. hasWon = true;
  1382.  
  1383. float duration = Time.time - startTime;
  1384. string durationString = string.Format("{0:0.00}", duration);
  1385. winText.text = "You won! Time: " + durationString;
  1386. }
  1387. else
  1388. {
  1389. hintText.text = "Not enough resources!";
  1390. hintText.gameObject.SetActive(true);
  1391. }
  1392. }
  1393. }
  1394.  
  1395. private void OnTriggerEnter(Collider other)
  1396. {
  1397. if (other.CompareTag("Resource"))
  1398. {
  1399. hintText.text = "Press " + interactKey.ToString() + " to gather resources";
  1400. hintText.gameObject.SetActive(true);
  1401. canInteract = true;
  1402. }
  1403. }
  1404.  
  1405. private void OnTriggerExit(Collider other)
  1406. {
  1407. if (other.CompareTag("Resource"))
  1408. {
  1409. hintText.gameObject.SetActive(false);
  1410. canInteract = false;
  1411. }
  1412. }
  1413.  
  1414. public void AddWood()
  1415. {
  1416. woodCount++;
  1417. }
  1418.  
  1419. public void AddStone()
  1420. {
  1421. stoneCount++;
  1422. }
  1423. }
  1424.  
  1425.  
  1426. This version adds a startTime variable in the Start method to store the time the game starts. Then, when the player wins, it calculates the duration of the game as Time.time - startTime and displays it in the winText UI element.
  1427. --------------------------
  1428. Great, that should be enough for our game ! Let's hope it will be successful
  1429. --------------------------
  1430. I hope so too! Good luck with your game development! Don't hesitate to reach out if you have any further questions or need assistance.
  1431. --------------------------
Advertisement
Add Comment
Please, Sign In to add comment