Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Let's make a game together. Give me an idea of a 3D game to create
- --------------------------
- Sure, here's an idea for a 3D game:
- Title: "Escape the Island"
- 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.
- Game Mechanics:
- Exploration - The player must explore the island to find resources, clues, and items that will help them escape.
- Resource Management - The player must manage their resources carefully, including food, water, and shelter.
- Crafting - The player can use the resources they find to craft tools, weapons, and other useful items.
- Puzzle-Solving - The player will encounter puzzles that must be solved to progress through the game.
- Survival - The player must avoid danger and maintain their health and energy levels in order to survive.
- Social Interaction - The player will encounter other characters on the island and must interact with them to gain information, assistance, or items.
- 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.
- I hope this idea inspires you to create an exciting and engaging 3D game!
- --------------------------
- I like this idea. Could you give me a script to move the player around ? It has to be in first person
- --------------------------
- Certainly! Here is an example script for moving the player around in a first-person perspective:
- csharp
- Copy code
- using UnityEngine;
- public class PlayerMovement : MonoBehaviour
- {
- public float moveSpeed = 5f; // speed at which the player moves
- public float jumpForce = 10f; // force of the player's jump
- public Transform groundCheck; // object representing the position of the ground check
- public float groundDistance = 0.4f; // distance from the ground check object to the ground
- public LayerMask groundMask; // layers that represent the ground
- Rigidbody rb;
- bool isGrounded = true;
- void Start()
- {
- rb = GetComponent<Rigidbody>();
- }
- void Update()
- {
- // get input for player movement
- float horizontal = Input.GetAxisRaw("Horizontal");
- float vertical = Input.GetAxisRaw("Vertical");
- // calculate movement vector
- Vector3 movement = transform.right * horizontal + transform.forward * vertical;
- movement = movement.normalized * moveSpeed * Time.deltaTime;
- // move the player
- rb.MovePosition(transform.position + movement);
- // check if player is on the ground
- isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
- // allow the player to jump if on the ground and spacebar is pressed
- if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
- {
- rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
- isGrounded = false;
- }
- }
- }
- 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!
- --------------------------
- The camera is not following the player, how could I do that ?
- --------------------------
- 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:
- csharp
- Copy code
- using UnityEngine;
- public class CameraFollow : MonoBehaviour
- {
- public Transform target; // player's Transform component
- public float smoothSpeed = 0.125f; // how smoothly the camera follows the player
- public Vector3 offset; // offset of the camera from the player
- void FixedUpdate()
- {
- // calculate target position for the camera
- Vector3 desiredPosition = target.position + offset;
- // smoothly move the camera to the target position
- Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
- transform.position = smoothedPosition;
- // make the camera always face the player
- transform.LookAt(target);
- }
- }
- 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.
- --------------------------
- The camera should move around with the mouse, how could I do that ?
- --------------------------
- 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:
- csharp
- Copy code
- using UnityEngine;
- public class CameraFollow : MonoBehaviour
- {
- public Transform target; // player's Transform component
- public float smoothSpeed = 0.125f; // how smoothly the camera follows the player
- public Vector3 offset; // offset of the camera from the player
- public float rotationSpeed = 100f; // how fast the camera rotates around the player
- float mouseX, mouseY;
- void LateUpdate()
- {
- // get mouse input for camera rotation
- mouseX += Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime;
- mouseY -= Input.GetAxis("Mouse Y") * rotationSpeed * Time.deltaTime;
- mouseY = Mathf.Clamp(mouseY, -80f, 80f); // clamp vertical rotation to prevent camera flipping
- // calculate rotation for camera
- Quaternion rotation = Quaternion.Euler(mouseY, mouseX, 0f);
- // calculate target position for the camera
- Vector3 desiredPosition = target.position + offset;
- // apply rotation to offset
- desiredPosition = rotation * offset;
- // smoothly move the camera to the target position
- Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
- transform.position = smoothedPosition;
- // make the camera always face the player
- transform.LookAt(target);
- }
- }
- 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.
- --------------------------
- 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
- --------------------------
- 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:
- csharp
- Copy code
- using UnityEngine;
- public class PlayerMovement : MonoBehaviour
- {
- public float moveSpeed = 5f;
- public float mouseSensitivity = 100f;
- float verticalRotation = 0f;
- CharacterController controller;
- void Start()
- {
- controller = GetComponent<CharacterController>();
- Cursor.lockState = CursorLockMode.Locked;
- }
- void Update()
- {
- // Get player input for movement
- float x = Input.GetAxis("Horizontal");
- float z = Input.GetAxis("Vertical");
- // Calculate movement vector based on input
- Vector3 move = transform.right * x + transform.forward * z;
- // Move the character controller
- controller.Move(move * moveSpeed * Time.deltaTime);
- // Get player input for rotation
- float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
- float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
- // Rotate the character horizontally
- transform.Rotate(Vector3.up * mouseX);
- // Calculate vertical rotation and apply to camera
- verticalRotation -= mouseY;
- verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
- Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
- }
- }
- 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.
- --------------------------
- That works ! How do I make the player affected by gravity ?
- --------------------------
- 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:
- csharp
- Copy code
- using UnityEngine;
- public class PlayerMovement : MonoBehaviour
- {
- public float moveSpeed = 5f;
- public float mouseSensitivity = 100f;
- public float gravity = -9.81f;
- float verticalRotation = 0f;
- CharacterController controller;
- void Start()
- {
- controller = GetComponent<CharacterController>();
- Cursor.lockState = CursorLockMode.Locked;
- }
- void Update()
- {
- // Get player input for movement
- float x = Input.GetAxis("Horizontal");
- float z = Input.GetAxis("Vertical");
- // Calculate movement vector based on input
- Vector3 move = transform.right * x + transform.forward * z;
- // Apply gravity to movement
- move.y = gravity;
- // Move the character controller
- controller.Move(move * moveSpeed * Time.deltaTime);
- // Get player input for rotation
- float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
- float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
- // Rotate the character horizontally
- transform.Rotate(Vector3.up * mouseX);
- // Calculate vertical rotation and apply to camera
- verticalRotation -= mouseY;
- verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
- Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
- }
- }
- In this updated script, the gravity variable controls the strength of the gravity. In the Update method, the script
- --------------------------
- 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
- --------------------------
- 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.
- 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:
- csharp
- Copy code
- using UnityEngine;
- using System.Collections.Generic;
- public class PlayerInventory : MonoBehaviour
- {
- public float maxPickupDistance = 2f;
- public KeyCode pickupKey = KeyCode.E;
- public List<GameObject> inventory = new List<GameObject>();
- private GameObject itemHeld;
- void Update()
- {
- // Check if player presses pickup key
- if (Input.GetKeyDown(pickupKey))
- {
- // Check if there's an object in front of the player that can be picked up
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, maxPickupDistance))
- {
- // Check if the object has a "Pickupable" tag
- if (hit.collider.CompareTag("Pickupable"))
- {
- // Add the object to the player's inventory
- inventory.Add(hit.collider.gameObject);
- // Remove the object from the scene
- hit.collider.gameObject.SetActive(false);
- }
- }
- }
- // Check if player is holding an item and presses pickup key again to drop it
- if (Input.GetKeyDown(pickupKey) && itemHeld != null)
- {
- // Drop the item
- itemHeld.SetActive(true);
- itemHeld.transform.position = transform.position + transform.forward * 1.5f;
- itemHeld = null;
- }
- // Check if player presses number keys to select items in inventory
- for (int i = 0; i < inventory.Count; i++)
- {
- if (Input.GetKeyDown((i + 1).ToString()))
- {
- // Drop any item that is currently being held
- if (itemHeld != null)
- {
- itemHeld.SetActive(true);
- itemHeld.transform.position = transform.position + transform.forward * 1.5f;
- }
- // Select the item in inventory and remove it from inventory list
- itemHeld = inventory[i];
- inventory.RemoveAt(i);
- break;
- }
- }
- }
- }
- 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.
- 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.
- --------------------------
- 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 ?
- --------------------------
- Sure! Here's an updated version of the script that includes a LayerMask to ignore certain objects:
- csharp
- Copy code
- using UnityEngine;
- using System.Collections.Generic;
- public class PlayerInventory : MonoBehaviour
- {
- public float maxPickupDistance = 2f;
- public KeyCode pickupKey = KeyCode.E;
- public List<GameObject> inventory = new List<GameObject>();
- private GameObject itemHeld;
- public LayerMask ignoreLayer;
- void Update()
- {
- // Check if player presses pickup key
- if (Input.GetKeyDown(pickupKey))
- {
- // Check if there's an object in front of the player that can be picked up
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, maxPickupDistance, ~ignoreLayer))
- {
- // Check if the object has a "Pickupable" tag
- if (hit.collider.CompareTag("Pickupable"))
- {
- // Add the object to the player's inventory
- inventory.Add(hit.collider.gameObject);
- // Remove the object from the scene
- hit.collider.gameObject.SetActive(false);
- }
- }
- }
- // Check if player is holding an item and presses pickup key again to drop it
- if (Input.GetKeyDown(pickupKey) && itemHeld != null)
- {
- // Drop the item
- itemHeld.SetActive(true);
- itemHeld.transform.position = transform.position + transform.forward * 1.5f;
- itemHeld = null;
- }
- // Check if player presses number keys to select items in inventory
- for (int i = 0; i < inventory.Count; i++)
- {
- if (Input.GetKeyDown((i + 1).ToString()))
- {
- // Drop any item that is currently being held
- if (itemHeld != null)
- {
- itemHeld.SetActive(true);
- itemHeld.transform.position = transform.position + transform.forward * 1.5f;
- }
- // Select the item in inventory and remove it from inventory list
- itemHeld = inventory[i];
- inventory.RemoveAt(i);
- break;
- }
- }
- }
- }
- 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.
- Make sure to assign a valid layer mask to the ignoreLayer variable in the Inspector.
- --------------------------
- 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.
- --------------------------
- Sure, here's a script that allows the player to interact with objects in the scene to gather resources (wood or stones):
- csharp
- Copy code
- using UnityEngine;
- public class ResourceGatherer : MonoBehaviour
- {
- public float maxInteractDistance = 2f;
- public KeyCode interactKey = KeyCode.E;
- void Update()
- {
- // Check if player presses interact key
- if (Input.GetKeyDown(interactKey))
- {
- // Check if there's an object in front of the player that can be interacted with
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance))
- {
- // Check if the object has a "Resource" tag
- if (hit.collider.CompareTag("Resource"))
- {
- // Get the resource type from the object's Resource component
- Resource resource = hit.collider.gameObject.GetComponent<Resource>();
- // Gather the resource
- int amountGathered = resource.Gather();
- // Add the resource to the player's inventory
- if (resource.resourceType == Resource.ResourceType.Wood)
- {
- Debug.Log("Gathered " + amountGathered + " wood.");
- // TODO: Add wood to player's inventory
- }
- else if (resource.resourceType == Resource.ResourceType.Stone)
- {
- Debug.Log("Gathered " + amountGathered + " stone.");
- // TODO: Add stone to player's inventory
- }
- }
- }
- }
- }
- }
- 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.
- 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.
- --------------------------
- Could you give me the script "Ressource" associated with this script ?
- --------------------------
- Sure, here's a sample Resource script that you could use:
- csharp
- Copy code
- using UnityEngine;
- public class Resource : MonoBehaviour
- {
- public enum ResourceType
- {
- Wood,
- Stone
- }
- public ResourceType resourceType;
- public int maxAmount = 10;
- public int amountLeft = 10;
- public int Gather()
- {
- int amountGathered = Mathf.Min(1, amountLeft); // Gather 1 unit or less if there's not enough left
- amountLeft -= amountGathered;
- if (amountLeft <= 0)
- {
- Destroy(gameObject);
- }
- return amountGathered;
- }
- }
- 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.
- 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.
- --------------------------
- We need to add a layermask system in ResourceGatherer to ignore certains objects that could get in the way
- --------------------------
- Sure, here's the updated ResourceGatherer script with a layer mask system:
- csharp
- Copy code
- using UnityEngine;
- public class ResourceGatherer : MonoBehaviour
- {
- public float maxInteractDistance = 2f;
- public KeyCode interactKey = KeyCode.E;
- public LayerMask interactLayerMask;
- void Update()
- {
- // Check if player presses interact key
- if (Input.GetKeyDown(interactKey))
- {
- // Check if there's an object in front of the player that can be interacted with
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance, interactLayerMask))
- {
- // Check if the object has a "Resource" tag
- if (hit.collider.CompareTag("Resource"))
- {
- // Get the resource type from the object's Resource component
- Resource resource = hit.collider.gameObject.GetComponent<Resource>();
- // Gather the resource
- int amountGathered = resource.Gather();
- // Add the resource to the player's inventory
- if (resource.resourceType == Resource.ResourceType.Wood)
- {
- Debug.Log("Gathered " + amountGathered + " wood.");
- // TODO: Add wood to player's inventory
- }
- else if (resource.resourceType == Resource.ResourceType.Stone)
- {
- Debug.Log("Gathered " + amountGathered + " stone.");
- // TODO: Add stone to player's inventory
- }
- }
- }
- }
- }
- }
- 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.
- 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")).
- --------------------------
- How could I store how many woods and stones I have in the script "ResourceGatherer" ?
- --------------------------
- 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:
- csharp
- Copy code
- using System.Collections.Generic;
- using UnityEngine;
- public class ResourceGatherer : MonoBehaviour
- {
- public float maxInteractDistance = 2f;
- public KeyCode interactKey = KeyCode.E;
- public LayerMask interactLayerMask;
- private Dictionary<Resource.ResourceType, int> inventory = new Dictionary<Resource.ResourceType, int>();
- private void Start()
- {
- // Initialize the inventory with 0 units of each resource type
- inventory[Resource.ResourceType.Wood] = 0;
- inventory[Resource.ResourceType.Stone] = 0;
- }
- void Update()
- {
- // Check if player presses interact key
- if (Input.GetKeyDown(interactKey))
- {
- // Check if there's an object in front of the player that can be interacted with
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance, interactLayerMask))
- {
- // Check if the object has a "Resource" tag
- if (hit.collider.CompareTag("Resource"))
- {
- // Get the resource type from the object's Resource component
- Resource resource = hit.collider.gameObject.GetComponent<Resource>();
- // Gather the resource
- int amountGathered = resource.Gather();
- // Add the resource to the player's inventory
- if (resource.resourceType == Resource.ResourceType.Wood)
- {
- Debug.Log("Gathered " + amountGathered + " wood.");
- inventory[Resource.ResourceType.Wood] += amountGathered;
- }
- else if (resource.resourceType == Resource.ResourceType.Stone)
- {
- Debug.Log("Gathered " + amountGathered + " stone.");
- inventory[Resource.ResourceType.Stone] += amountGathered;
- }
- }
- }
- }
- }
- }
- 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].
- --------------------------
- is there a way to display the inventory content in the inspector ?
- --------------------------
- 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:
- csharp
- Copy code
- using System.Collections.Generic;
- using UnityEngine;
- public class ResourceGatherer : MonoBehaviour
- {
- public float maxInteractDistance = 2f;
- public KeyCode interactKey = KeyCode.E;
- public LayerMask interactLayerMask;
- [SerializeField]
- private InventoryData inventoryData;
- private Dictionary<Resource.ResourceType, int> inventory;
- private void Awake()
- {
- inventory = inventoryData.inventory;
- }
- void Update()
- {
- // Check if player presses interact key
- if (Input.GetKeyDown(interactKey))
- {
- // Check if there's an object in front of the player that can be interacted with
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance, interactLayerMask))
- {
- // Check if the object has a "Resource" tag
- if (hit.collider.CompareTag("Resource"))
- {
- // Get the resource type from the object's Resource component
- Resource resource = hit.collider.gameObject.GetComponent<Resource>();
- // Gather the resource
- int amountGathered = resource.Gather();
- // Add the resource to the player's inventory
- if (resource.resourceType == Resource.ResourceType.Wood)
- {
- Debug.Log("Gathered " + amountGathered + " wood.");
- inventory[Resource.ResourceType.Wood] += amountGathered;
- }
- else if (resource.resourceType == Resource.ResourceType.Stone)
- {
- Debug.Log("Gathered " + amountGathered + " stone.");
- inventory[Resource.ResourceType.Stone] += amountGathered;
- }
- }
- }
- }
- }
- }
- [System.Serializable]
- public class InventoryData
- {
- public Dictionary<Resource.ResourceType, int> inventory = new Dictionary<Resource.ResourceType, int>
- {
- { Resource.ResourceType.Wood, 0 },
- { Resource.ResourceType.Stone, 0 }
- };
- }
- 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.
- 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.
- --------------------------
- I'm now using this proposition, the previous one was good enough. How can I display the current player's ressources on screen ?
- --------------------------
- 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.
- Here's an updated version of the ResourceGatherer script that includes a private Text variable for displaying the player's resources on screen:
- csharp
- Copy code
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- public class ResourceGatherer : MonoBehaviour
- {
- public float maxInteractDistance = 2f;
- public KeyCode interactKey = KeyCode.E;
- public LayerMask interactLayerMask;
- [SerializeField]
- private Text inventoryText;
- private Dictionary<Resource.ResourceType, int> inventory;
- private void Awake()
- {
- inventory = new Dictionary<Resource.ResourceType, int>
- {
- { Resource.ResourceType.Wood, 0 },
- { Resource.ResourceType.Stone, 0 }
- };
- }
- void Update()
- {
- // Check if player presses interact key
- if (Input.GetKeyDown(interactKey))
- {
- // Check if there's an object in front of the player that can be interacted with
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, maxInteractDistance, interactLayerMask))
- {
- // Check if the object has a "Resource" tag
- if (hit.collider.CompareTag("Resource"))
- {
- // Get the resource type from the object's Resource component
- Resource resource = hit.collider.gameObject.GetComponent<Resource>();
- // Gather the resource
- int amountGathered = resource.Gather();
- // Add the resource to the player's inventory
- if (resource.resourceType == Resource.ResourceType.Wood)
- {
- Debug.Log("Gathered " + amountGathered + " wood.");
- inventory[Resource.ResourceType.Wood] += amountGathered;
- }
- else if (resource.resourceType == Resource.ResourceType.Stone)
- {
- Debug.Log("Gathered " + amountGathered + " stone.");
- inventory[Resource.ResourceType.Stone] += amountGathered;
- }
- // Update the inventory text
- UpdateInventoryText();
- }
- }
- }
- }
- private void UpdateInventoryText()
- {
- // Build a string with the current inventory contents
- string inventoryString = "Inventory:\n";
- inventoryString += "Wood: " + inventory[Resource.ResourceType.Wood] + "\n";
- inventoryString += "Stone: " + inventory[Resource.ResourceType.Stone];
- // Update the text component
- inventoryText.text = inventoryString;
- }
- }
- 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.
- In the Update method, the `Update
- --------------------------
- Great, I now need a script with which the player can interact if the inventory contains 2 woods and 2 stones
- --------------------------
- Sure, here's an example script that checks the player's inventory and allows interaction if it contains 2 woods and 2 stones:
- csharp
- Copy code
- using UnityEngine;
- public class InteractionChecker : MonoBehaviour
- {
- public ResourceGatherer resourceGatherer;
- public GameObject interactableObject;
- public KeyCode interactKey = KeyCode.E;
- private bool hasInteracted = false;
- void Update()
- {
- if (!hasInteracted)
- {
- // Check if the player has 2 woods and 2 stones in their inventory
- if (resourceGatherer.GetResourceCount(Resource.ResourceType.Wood) >= 2
- && resourceGatherer.GetResourceCount(Resource.ResourceType.Stone) >= 2)
- {
- // Display a message to the player to interact with the object
- Debug.Log("You can interact with the object now.");
- // Check if the player presses the interact key
- if (Input.GetKeyDown(interactKey))
- {
- // Interact with the object
- Debug.Log("Interacting with the object...");
- interactableObject.GetComponent<Interactable>().Interact();
- // Remove 2 woods and 2 stones from the player's inventory
- resourceGatherer.RemoveResource(Resource.ResourceType.Wood, 2);
- resourceGatherer.RemoveResource(Resource.ResourceType.Stone, 2);
- // Set the hasInteracted flag to true to prevent further interactions
- hasInteracted = true;
- }
- }
- }
- }
- }
- 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.
- 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.
- --------------------------
- The methods "GetResourceCount" and "RemoveResource" does not exist in ResourceGatherer, could you make them ?
- --------------------------
- Sure, here's an updated version of the ResourceGatherer script with the GetResourceCount and RemoveResource methods implemented:
- csharp
- Copy code
- using System.Collections.Generic;
- using UnityEngine;
- public class ResourceGatherer : MonoBehaviour
- {
- // Define a dictionary to store the player's resources
- private Dictionary<Resource.ResourceType, int> resources = new Dictionary<Resource.ResourceType, int>();
- void Start()
- {
- // Initialize the dictionary with all resource types and a count of 0 for each
- foreach (Resource.ResourceType resourceType in System.Enum.GetValues(typeof(Resource.ResourceType)))
- {
- resources[resourceType] = 0;
- }
- }
- // Add a given amount of a given resource to the player's inventory
- public void AddResource(Resource.ResourceType resourceType, int amount)
- {
- resources[resourceType] += amount;
- }
- // Get the current count of a given resource in the player's inventory
- public int GetResourceCount(Resource.ResourceType resourceType)
- {
- return resources[resourceType];
- }
- // Remove a given amount of a given resource from the player's inventory
- public void RemoveResource(Resource.ResourceType resourceType, int amount)
- {
- resources[resourceType] -= amount;
- // Make sure the resource count doesn't go below 0
- if (resources[resourceType] < 0)
- {
- resources[resourceType] = 0;
- }
- }
- }
- 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.
- The Start method initializes the dictionary with all resource types and a count of
- --------------------------
- In the script InteractionChecker, please replace the line "interactableObject.GetComponent<Interactable>().Interact();" by a line enabling a gameobject instead
- --------------------------
- Sure! Here's an updated version of the InteractionChecker script with the requested change:
- csharp
- Copy code
- using UnityEngine;
- public class InteractionChecker : MonoBehaviour
- {
- public float interactionDistance = 2f;
- public LayerMask interactableLayer;
- private Camera mainCamera;
- void Start()
- {
- mainCamera = Camera.main;
- }
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.E))
- {
- RaycastHit hit;
- if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, interactionDistance, interactableLayer))
- {
- GameObject interactableObject = hit.collider.gameObject;
- // Enable the gameobject instead of calling Interact method
- interactableObject.SetActive(true);
- }
- }
- }
- }
- 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.
- 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.
- --------------------------
- the object to enable should be stored in a variable
- --------------------------
- Sure! Here's an updated version of the InteractionChecker script that stores the interactable object in a variable before enabling it:
- csharp
- Copy code
- using UnityEngine;
- public class InteractionChecker : MonoBehaviour
- {
- public float interactionDistance = 2f;
- public LayerMask interactableLayer;
- private Camera mainCamera;
- private GameObject interactableObject;
- void Start()
- {
- mainCamera = Camera.main;
- }
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.E))
- {
- RaycastHit hit;
- if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, interactionDistance, interactableLayer))
- {
- interactableObject = hit.collider.gameObject;
- // Disable collider to prevent further interactions
- interactableObject.GetComponent<Collider>().enabled = false;
- // Enable the gameobject instead of calling Interact method
- interactableObject.SetActive(true);
- }
- }
- }
- }
- 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.
- Then, before enabling the object, I disabled its collider to prevent further interactions. Finally, I enabled the gameobject as before with interactableObject.SetActive(true);.
- --------------------------
- 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.
- --------------------------
- Sure! Here's an example script that should accomplish what you're looking for:
- csharp
- Copy code
- using UnityEngine;
- public class ObjectInteractor : MonoBehaviour
- {
- public GameObject replacementObject;
- public int requiredWood = 2;
- public int requiredStone = 2;
- private ResourceGatherer resourceGatherer;
- void Start()
- {
- resourceGatherer = GetComponent<ResourceGatherer>();
- }
- void OnTriggerEnter(Collider other)
- {
- if (CheckRequirements() && other.CompareTag("Interactable"))
- {
- // Destroy the current object and activate the replacement object
- Destroy(other.gameObject);
- replacementObject.SetActive(true);
- // Remove the required resources from the inventory
- resourceGatherer.RemoveResource("Wood", requiredWood);
- resourceGatherer.RemoveResource("Stone", requiredStone);
- }
- }
- bool CheckRequirements()
- {
- int woodCount = resourceGatherer.GetResourceCount("Wood");
- int stoneCount = resourceGatherer.GetResourceCount("Stone");
- return woodCount >= requiredWood && stoneCount >= requiredStone;
- }
- }
- 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.
- 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);.
- --------------------------
- Not bad but I'd like the player to interact by pressing a key not by using OnTriggerEnter
- --------------------------
- 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:
- csharp
- Copy code
- using UnityEngine;
- using UnityEngine.InputSystem;
- public class ObjectInteractor : MonoBehaviour
- {
- public GameObject replacementObject;
- public int requiredWood = 2;
- public int requiredStone = 2;
- public KeyCode interactKey = KeyCode.E;
- private ResourceGatherer resourceGatherer;
- private Collider currentObject;
- void Start()
- {
- resourceGatherer = GetComponent<ResourceGatherer>();
- }
- void Update()
- {
- if (currentObject != null && Keyboard.current[interactKey].wasPressedThisFrame)
- {
- if (CheckRequirements())
- {
- // Destroy the current object and activate the replacement object
- Destroy(currentObject.gameObject);
- replacementObject.SetActive(true);
- // Remove the required resources from the inventory
- resourceGatherer.RemoveResource("Wood", requiredWood);
- resourceGatherer.RemoveResource("Stone", requiredStone);
- currentObject = null;
- }
- }
- }
- void OnTriggerEnter(Collider other)
- {
- if (other.CompareTag("Interactable"))
- {
- currentObject = other;
- }
- }
- void OnTriggerExit(Collider other)
- {
- if (other == currentObject)
- {
- currentObject = null;
- }
- }
- bool CheckRequirements()
- {
- int woodCount = resourceGatherer.GetResourceCount("Wood");
- int stoneCount = resourceGatherer.GetResourceCount("Stone");
- return woodCount >= requiredWood && stoneCount >= requiredStone;
- }
- }
- 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.
- We're also using the OnTriggerEnter and OnTriggerExit methods to keep track of the current object that the player is able to interact with.
- --------------------------
- This script is not what we want. Let's try another way.
- 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.
- --------------------------
- Sure, here's a script that should accomplish that:
- csharp
- Copy code
- using UnityEngine;
- public class InteractWithObject : MonoBehaviour
- {
- public KeyCode interactKey = KeyCode.E;
- public int woodNeeded = 2;
- public int stoneNeeded = 2;
- public GameObject objectToDisable;
- public GameObject objectToEnable;
- private ResourceGatherer resourceGatherer;
- private void Start()
- {
- resourceGatherer = GetComponent<ResourceGatherer>();
- }
- private void Update()
- {
- if (Input.GetKeyDown(interactKey))
- {
- if (resourceGatherer.GetResourceCount(ResourceType.Wood) >= woodNeeded && resourceGatherer.GetResourceCount(ResourceType.Stone) >= stoneNeeded)
- {
- resourceGatherer.RemoveResource(ResourceType.Wood, woodNeeded);
- resourceGatherer.RemoveResource(ResourceType.Stone, stoneNeeded);
- objectToDisable.SetActive(false);
- objectToEnable.transform.GetChild(0).gameObject.SetActive(true);
- }
- }
- }
- }
- 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.
- --------------------------
- This should work but I want the player to look at the object to disable AND press the interact key
- --------------------------
- Sure, here's an updated script that requires the player to look at the object and press the interact key:
- csharp
- Copy code
- using UnityEngine;
- public class InteractWithObject : MonoBehaviour
- {
- public KeyCode interactKey = KeyCode.E;
- public int woodNeeded = 2;
- public int stoneNeeded = 2;
- public GameObject objectToDisable;
- public GameObject objectToEnable;
- public float interactionRange = 3f;
- private ResourceGatherer resourceGatherer;
- private void Start()
- {
- resourceGatherer = GetComponent<ResourceGatherer>();
- }
- private void Update()
- {
- if (Input.GetKeyDown(interactKey))
- {
- RaycastHit hit;
- if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, interactionRange))
- {
- if (hit.collider.gameObject == objectToDisable && resourceGatherer.GetResourceCount(ResourceType.Wood) >= woodNeeded && resourceGatherer.GetResourceCount(ResourceType.Stone) >= stoneNeeded)
- {
- resourceGatherer.RemoveResource(ResourceType.Wood, woodNeeded);
- resourceGatherer.RemoveResource(ResourceType.Stone, stoneNeeded);
- objectToDisable.SetActive(false);
- objectToEnable.transform.GetChild(0).gameObject.SetActive(true);
- }
- }
- }
- }
- }
- 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.
- --------------------------
- Remember the script ResourceGatherer ? I'd like to display a text on screen when the player looks at an object with the tag "Resource"
- --------------------------
- Sure! You can add the following script to the player camera and attach a UI Text object to it:
- csharp
- Copy code
- using UnityEngine;
- using UnityEngine.UI;
- public class ResourceText : MonoBehaviour
- {
- public float maxDistance = 5f; // Maximum distance to detect resources
- public LayerMask layerMask; // Layer mask to detect resources
- public Text textObject; // UI text object to display the message
- private void Update()
- {
- // Cast a ray from the center of the screen
- Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
- RaycastHit hit;
- if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
- {
- // If the ray hits a resource object, display the message
- if (hit.collider.CompareTag("Resource"))
- {
- textObject.text = "Press E to gather resources";
- textObject.gameObject.SetActive(true);
- }
- else
- {
- textObject.gameObject.SetActive(false);
- }
- }
- else
- {
- textObject.gameObject.SetActive(false);
- }
- }
- }
- 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.
- --------------------------
- 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
- --------------------------
- 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.
- Here's the updated code:
- C#
- Copy code
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class InteractWithObject : MonoBehaviour
- {
- public KeyCode interactKey = KeyCode.E;
- public int woodNeeded = 2;
- public int stoneNeeded = 2;
- public GameObject objectToDisable;
- public GameObject objectToEnable;
- public GameObject notEnoughResourcesText;
- private ResourceGatherer resourceGatherer;
- private void Start()
- {
- resourceGatherer = GetComponent<ResourceGatherer>();
- }
- private void Update()
- {
- if (Input.GetKeyDown(interactKey))
- {
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, 3f))
- {
- if (hit.transform.CompareTag("Resource"))
- {
- if (resourceGatherer.GetResourceCount(ResourceType.Wood) >= woodNeeded
- && resourceGatherer.GetResourceCount(ResourceType.Stone) >= stoneNeeded)
- {
- resourceGatherer.RemoveResource(ResourceType.Wood, woodNeeded);
- resourceGatherer.RemoveResource(ResourceType.Stone, stoneNeeded);
- objectToDisable.SetActive(false);
- objectToEnable.SetActive(true);
- }
- else
- {
- notEnoughResourcesText.SetActive(true);
- StartCoroutine(HideText());
- }
- }
- }
- }
- }
- private IEnumerator HideText()
- {
- yield return new WaitForSeconds(2f);
- notEnoughResourcesText.SetActive(false);
- }
- }
- 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.
- 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.
- --------------------------
- In this same script, when calling "objectToEnable.SetActive(true);" we should also display a text on screen indicating to the player that he won
- --------------------------
- Sure, here's an updated version of the InteractWithObject script that includes the text display when the player wins:
- csharp
- Copy code
- using UnityEngine;
- using UnityEngine.UI;
- public class InteractWithObject : MonoBehaviour
- {
- public KeyCode interactKey = KeyCode.E;
- public int requiredWood = 2;
- public int requiredStone = 2;
- public GameObject objectToDisable;
- public GameObject objectToEnable;
- public Text messageText;
- private ResourceGatherer resourceGatherer;
- private void Start()
- {
- resourceGatherer = GetComponent<ResourceGatherer>();
- }
- private void Update()
- {
- if (Input.GetKeyDown(interactKey))
- {
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit, 3f))
- {
- if (hit.transform.CompareTag("Resource"))
- {
- int woodCount = resourceGatherer.GetResourceCount(ResourceType.Wood);
- int stoneCount = resourceGatherer.GetResourceCount(ResourceType.Stone);
- if (woodCount >= requiredWood && stoneCount >= requiredStone)
- {
- resourceGatherer.RemoveResource(ResourceType.Wood, requiredWood);
- resourceGatherer.RemoveResource(ResourceType.Stone, requiredStone);
- objectToDisable.SetActive(false);
- objectToEnable.SetActive(true);
- messageText.text = "You won!";
- }
- else
- {
- messageText.text = "You need more resources.";
- }
- }
- }
- }
- }
- }
- 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."
- --------------------------
- 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
- --------------------------
- Sure, here's an updated version of the InteractWithObject script with a timer:
- csharp
- Copy code
- using UnityEngine;
- using UnityEngine.UI;
- public class InteractWithObject : MonoBehaviour
- {
- public KeyCode interactKey = KeyCode.E;
- public LayerMask interactableMask;
- public Text hintText;
- public Text winText;
- public int woodNeeded = 2;
- public int stoneNeeded = 2;
- public GameObject objectToDisable;
- public GameObject objectToEnable;
- private int woodCount = 0;
- private int stoneCount = 0;
- private bool canInteract = false;
- private bool hasWon = false;
- private float startTime;
- private void Start()
- {
- startTime = Time.time;
- }
- private void Update()
- {
- if (canInteract && !hasWon && Input.GetKeyDown(interactKey))
- {
- if (woodCount >= woodNeeded && stoneCount >= stoneNeeded)
- {
- objectToDisable.SetActive(false);
- objectToEnable.SetActive(true);
- hintText.gameObject.SetActive(false);
- winText.gameObject.SetActive(true);
- hasWon = true;
- float duration = Time.time - startTime;
- string durationString = string.Format("{0:0.00}", duration);
- winText.text = "You won! Time: " + durationString;
- }
- else
- {
- hintText.text = "Not enough resources!";
- hintText.gameObject.SetActive(true);
- }
- }
- }
- private void OnTriggerEnter(Collider other)
- {
- if (other.CompareTag("Resource"))
- {
- hintText.text = "Press " + interactKey.ToString() + " to gather resources";
- hintText.gameObject.SetActive(true);
- canInteract = true;
- }
- }
- private void OnTriggerExit(Collider other)
- {
- if (other.CompareTag("Resource"))
- {
- hintText.gameObject.SetActive(false);
- canInteract = false;
- }
- }
- public void AddWood()
- {
- woodCount++;
- }
- public void AddStone()
- {
- stoneCount++;
- }
- }
- 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.
- --------------------------
- Great, that should be enough for our game ! Let's hope it will be successful
- --------------------------
- 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.
- --------------------------
Advertisement
Add Comment
Please, Sign In to add comment