Search code examples
listunity-game-enginegeneratecollect

How to connect my collectable items with the random generator and use a list of words for generating in UNITY 2D


I have a script for random word generating:

public TextMeshPro largeText;

    public void BtnAction()
    {
        CreateRandomString();
    }

    private void CreateRandomString(int stringLength = 10)
    {
        int _stringLength = stringLength - 1;
        string randomString = "";
        string[] characters = new string[] { "A", "B", "C", "D" };
        for (int i = 0; i<= _stringLength; i++)
        {
            randomString = randomString + characters[Random.Range(0, characters.Length)];
        }
        largeText.text = randomString;
    }

In my game, the player has to collect letters, which I have made with a tag of collectables, to use in the inventory system for gathering.

private void OnTriggerEnter2D(Collider2D other)
    {

        if(other.CompareTag("Collectable"))
        {
            string inventoryType = other.gameObject.GetComponent<Collectable>().inventoryType;
            print("We have collected a:"+ inventoryType);

            inventory.Add(inventoryType);
            print("Inventory length:" + inventory.Count);
            Destroy(other.gameObject);

            string wordType = other.gameObject.GetComponent<Collectable>().inventoryType;
        }
    }

I want instead of:

string[] characters = new string[] { "A", "B", "C", "D" };

the string to be from the gathered letters.

After that, to be generated a word from an existing list with words.

How do I do that?


Solution

  • In your OnTriggerEnter script you can store the letters in an List like this,

    //Instantiate your List
    public List<string> mylist = new List<string>();
    
    //Add the letters to your List 
    mylist.Add(other.gameObject.GetComponent<Collectable>().inventoryType);
    

    Then you have to refernce List to your other function that generates the random string(I'm assuming you know how to do this,I can't give you a specific method because I don't know the arrangement on your side).Its easy if both these functions are in one script.

    If the functions are in two different scripts you have to reference the GameObject with the first script to your second script in the inspector and then

    public GameObject GameObject_with_your_first_Script;
    ......
    
    
    firstScriptClassName myScript = GameObject_with_your_first_Script.GetComponent<fistScriptClassName>();
    
    List referencedList = myScript.mylist;
    

    Hope this is helpful.I've mentioned the bare essentials you need to get what you want done..Let me know If anything is not clear.