Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

I will share 3 scripts consisting of a puzzle. In the PlayerInteraction script, instead…

  1. User

    I will share 3 scripts consisting of a puzzle. In the PlayerInteraction script, instead of pressing E to call the Interact() function, i want to press E to call a OnGUI function in which I loop through my player inventory and list all of the name items containing the EldritchSymbol component. When the player click on one of the available item in the list, then it will call the Interact() function, and the player will place the item he clicked on under the current symbol transform. Also, I need anothe OnGUI function that list the name of the item in the symbol slot, and when the player clicks it, it returns back to the player inventory. I want the GUI to be center screen.

    Script 1: using System.Collections; using System.Collections.Generic; using UnityEngine;

    public class LovecraftianPuzzle : MonoBehaviour { public enum EldritchSymbols { Nyarlathotep, Azathoth, Cthulhu, ShubNiggurath, YogSothoth } public Transform[] symbolSlots; public GameObject[] eldritchSymbolPrefabs; public GameObject portal; public Animator portalAnimator; public AudioSource gatewayAudio; public AudioClip placeSymbolSound; private GameObject player; private AudioSource playerAudioSource;

    private void Start() { player = GameObject.Find("Player"); playerAudioSource = player.GetComponent(); } private List correctOrder = new List() { EldritchSymbols.Nyarlathotep, EldritchSymbols.Azathoth, EldritchSymbols.Cthulhu, EldritchSymbols.ShubNiggurath, EldritchSymbols.YogSothoth };

    private List currentOrder = new List();

    private Dictionary<EldritchSymbols, int> symbolToSlotIndex = new Dictionary<EldritchSymbols, int>() { { EldritchSymbols.Nyarlathotep, 0 }, { EldritchSymbols.Cthulhu, 2 }, { EldritchSymbols.Azathoth, 1 }, { EldritchSymbols.ShubNiggurath, 3 }, { EldritchSymbols.YogSothoth, 4 } }; public void PlaceSymbol(EldritchSymbols symbol) { int slotIndex = symbolToSlotIndex[symbol]; if (symbolSlots[slotIndex].childCount == 0) { GameObject symbolObject = Instantiate( eldritchSymbolPrefabs[(int)symbol], symbolSlots[slotIndex].position, Quaternion.Euler(0, 24, -90), // Rotate 90 degrees around the Z axis symbolSlots[slotIndex]); if (!currentOrder.Contains(symbol)) // Check if the symbol is already in the list { currentOrder.Add(symbol); // Add it only if it's not present } playerAudioSource.PlayOneShot(placeSymbolSound); }

    CheckPuzzleSolved();
    

    }

    private void CheckPuzzleSolved() { if (currentOrder.Count == correctOrder.Count) { bool isSolved = true;

        for (int i = 0; i < correctOrder.Count; i++)
        {
            if (currentOrder[i] != correctOrder[i])
            {
                isSolved = false;
                break;
            }
        }
    
        if (isSolved)
        {
            StartCoroutine(GatewayAnimation());
        }
    }
    

    } public IEnumerator GatewayAnimation() { portalAnimator.SetBool("OpenGateway", true); MeshCollider gatewayMeshFilter = portalAnimator.gameObject.GetComponent(); gatewayAudio.Play(); gatewayMeshFilter.enabled = false; yield return new WaitForSeconds(1f); portalAnimator.SetBool("OpenGateway", false); }

    public void ResetPuzzle() { currentOrder.Clear();

    foreach (Transform slot in symbolSlots)
    {
        if (slot.childCount > 0)
        {
            Destroy(slot.GetChild(0).gameObject);
        }
    }
    

    }

    public void RemoveSymbol(EldritchSymbols symbol) { // Find the index of the symbol in the currentOrder list int index = currentOrder.FindIndex(s => s == symbol);

    // Check that the index is valid
    if (index >= 0 && index < currentOrder.Count)
    {
        // Find the corresponding symbol in the symbolSlots array
        for (int i = 0; i < symbolSlots.Length; i++)
        {
            if (symbolSlots[i].childCount > 0)
            {
                GameObject symbolObject = symbolSlots[i].GetChild(0).gameObject;
                EldritchSymbols symbolInSlot = symbolObject.GetComponent<EldritchSymbol>().symbolType;
    
                if (symbolInSlot == symbol)
                {
                    // Remove the symbol from currentOrder and destroy the symbol object
                    currentOrder.RemoveAt(index);
                    playerAudioSource.PlayOneShot(placeSymbolSound);
                    Destroy(symbolObject);
                    break;
                }
            }
        }
    }
    

    } }

    Script 2: using UnityEngine;

    public class EldritchSymbol : MonoBehaviour { public LovecraftianPuzzle.EldritchSymbols symbolType; }

    Script 3: using System.Collections; using System.Collections.Generic; using UnityEngine;

    public class PlayerInteraction : MonoBehaviour { public float interactionDistance = 2f; public LayerMask interactionMask; private GameObject currentInteractable; private GameObject lastPlacedSymbol; void Update() { if (Input.GetKeyDown(KeyCode.E)) { Interact(); } }

    void FixedUpdate() { CheckForInteractions(); }

    void CheckForInteractions() { RaycastHit hitInfo; if (Physics.Raycast(transform.position, transform.forward, out hitInfo, interactionDistance, interactionMask)) { if (hitInfo.transform.gameObject != currentInteractable) { currentInteractable = hitInfo.transform.gameObject; Debug.Log("New Interactable: " + currentInteractable.name);

            // You can add visual feedback or highlighting for the interactable object here.
        }
    }
    /*else
    {
        if (currentInteractable != null)
        {
            currentInteractable = null;
            Debug.Log("No interactable object in range.");
    
            // You can remove visual feedback or highlighting for the interactable object here.
        }
    }*/
    

    }

    void Interact() { if (currentInteractable != null) { EldritchSymbol symbol = currentInteractable.GetComponent(); if (symbol != null) { LovecraftianPuzzle puzzle = FindObjectOfType(); if (puzzle != null) { if (lastPlacedSymbol == currentInteractable) { puzzle.RemoveSymbol(symbol.symbolType); lastPlacedSymbol = null; // Reset the last placed symbol } else { puzzle.PlaceSymbol(symbol.symbolType); lastPlacedSymbol = currentInteractable; // Store the placed symbol } } } } } }

    Here's an exemple on how I loop for Item name in my Inventory: for (int t = 0; t < InvManager.Items; t++) //Starting a loop in the slots of the inventory: { if (InvManager.Slots[t].IsTaken == true) //Checking if there's an item in this slot. { Item ItemScript = InvManager.Slots[t].Item.GetComponent(); //Getting the item script from the items inside the bag. if (ItemScript.Name == "ExempleName"){//Do stuff}

  2. Assistant

    To implement the GUI interaction as you've described, follow these steps:

    1. Modify the PlayerInteraction script to detect when KeyCode.E is pressed and if currentInteractable exists, instead of calling Interact() it should enable GUI interaction.
    2. Add a list to keep track of items with EldritchSymbol components in the player's inventory.
    3. Implement the OnGUI() method in PlayerInteraction, which will display a selectable list of items with EldritchSymbol components.
    4. Add another OnGUI() method to display the interactive item if it's an Eldritch Symbol that's currently in a puzzle slot.
    5. Implement the logic for clicking on items in the GUI list to place or remove them from the slots.

    Here's how you might update PlayerInteraction script (some parts are assumed based on your initial description, like access to the Inventory Manager):

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class PlayerInteraction : MonoBehaviour
    {
        // ... existing variables ...
    
        private List<GameObject> eldritchInventoryItems = new List<GameObject>();
        private bool showInventoryGUI = false;
        private LovecraftianPuzzle puzzle;
    
        private void Start()
        {
            puzzle = FindObjectOfType<LovecraftianPuzzle>(); // Cache this since it won't change
        }
    
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.E) && currentInteractable != null)
            {
                // Instead of interacting directly, we'll set the flag to show the GUI
                showInventoryGUI = true;
                // Populate the inventory list
                UpdateEldritchInventoryItems(); 
            }
        }
    
        // ... existing methods ...
    
        private void UpdateEldritchInventoryItems()
        {
            eldritchInventoryItems.Clear();
            for (int t = 0; t < InvManager.Items; t++) // Assuming InvManager is accessible
            {
                if (InvManager.Slots[t].IsTaken)
                {
                    GameObject item = InvManager.Slots[t].Item;
                    EldritchSymbol symbol = item.GetComponent<EldritchSymbol>();
                    if (symbol)
                    {
                        eldritchInventoryItems.Add(item);
                    }
                }
            }
        }
    
        private void OnGUI()
        {
            if (showInventoryGUI)
            {
                // Create a centered GUI box to list inventory EldritchSymbols
                float width = 200;
                float height = 25 * eldritchInventoryItems.Count;
                Rect rect = new Rect((Screen.width - width) / 2, (Screen.height - height) / 2, width, height);
                GUILayout.BeginArea(rect, GUI.skin.box);
                
                foreach (var item in eldritchInventoryItems)
                {
                    if (GUILayout.Button(item.name))
                    {
                        EldritchSymbol symbol = item.GetComponent<EldritchSymbol>();
                        if (puzzle)
                        {
                            puzzle.PlaceSymbol(symbol.symbolType, currentInteractable.transform);
                            showInventoryGUI = false;
                        }
                    }
                }
    
                GUILayout.EndArea();
            }
    
            // Add similar GUI logic here to show the current symbol in a slot, with click-to-remove functionality
        }
    
        // Modify this method to handle placement with a Transform parameter for where to place it.
        public void PlaceEldritchItemInSlot(GameObject item, Transform slot)
        {
            // Your logic to place the item in the slot
        }
    
        // You might also need a method to remove items from slots if there is interaction for that
    }
    

    Remember to handle toggling showInventoryGUI on and off as needed. You might also need additional methods to handle returning an item to the inventory when it's removed from a slot. The GUI code will create a centered box and list the inventory items. You should customize the appearance and position as needed for your game's look and feel.

    Make sure your LovecraftianPuzzle is set up to handle placement based on the transform indicated, and adjust any necessary logic involved in symbol placement and removal. This script is a starting point, and you should expand it in a way that integrates with the rest of your game's systems.

  3. User

    GameObject item = InvManager.Slots[t].Item; Impossible de convertir implicitement Transform en GameObject

  4. Assistant

    Apologies for the oversight. It seems that I've made an incorrect assumption about the type contained in InvManager.Slots[t].Item. If this is returning a Transform, you need to access its corresponding GameObject using the .gameObject property. Given that you cannot implicitly convert a Transform to a GameObject, let's fix this:

    Replace the line:

    GameObject item = InvManager.Slots[t].Item;
    

    with:

    GameObject item = InvManager.Slots[t].Item.gameObject;
    

    This should correctly assign the GameObject associated with the Transform to the variable item. The updated part of the UpdateEldritchInventoryItems method should look like this:

    private void UpdateEldritchInventoryItems()
    {
        eldritchInventoryItems.Clear();
        for (int t = 0; t < InvManager.Items; t++) // Assuming InvManager is accessible
        {
            if (InvManager.Slots[t].IsTaken)
            {
                GameObject item = InvManager.Slots[t].Item.gameObject; // Corrected line
                EldritchSymbol symbol = item.GetComponent<EldritchSymbol>();
                if (symbol)
                {
                    eldritchInventoryItems.Add(item);
                }
            }
        }
    }
    

    Be sure to validate that InvManager.Slots[t].Item is indeed a Transform that has a .gameObject property available. If InvManager.Slots[t].Item is of a different type, then you should adjust the code accordingly to get the GameObject reference.