Застряли в сравнении случайно сгенерированной строки с именем / тегом игрового объекта? - PullRequest
0 голосов
/ 05 августа 2020

Разработка небольшой игры, в которой будет сгенерировано случайное имя, отображаемое в текстовом пространстве, и игрок должен столкнуться с объектом с именем, отображаемым в текстовом пространстве. Например, если отображается «лимон», игрок должен коснуться игрового объекта «лимон», расположенного на столе.

   using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    public class RandomString : MonoBehaviour
    {
        [SerializeField] Text randName;
        public GameObject[] veggies;
        string[] veg = { "Olive", "Lemon", "Carrot" };
    
        void Start()
        {
            randName.text = veg[1];
        }
    
        void Update()
        {
            GenerateRandom(3);
    
        }
        private void GenerateRandom(int maxInt)
        {
            int rnd = UnityEngine.Random.Range(0, maxInt);
            if (Input.GetKey(KeyCode.Space))
            {
                string a =  veg[rnd];
                randName.text = a;
    
            }
        }
        void OnCollisionEnter(Collision col, string a)
        {
            if (col.gameObject.CompareTag(a))
            {
                Debug.Log("Hit");
            }
        }
    
    }

1 Ответ

0 голосов
/ 05 августа 2020

Почему вы постоянно генерируете новое случайное значение, даже если вам нужно только одно внутри блока if(Input.GetKey) ...

Тогда также: вы действительно хотите назначать новое случайное значение каждый кадр кнопке остается нажатым? Разве в первый раз не будет достаточно (GetKeyDown)?

И тогда вы не сможете просто изменить подпись OnCollisionEnter(Collider), иначе этот метод сообщения не распознается Unity и не вызывается.

Я думаю, что это должно быть

// Store the random string in class scope
string a;

private void Start()
{
    GenerateRandom ();
}

private void Update()
{
    // While debugging I assume you will use this
    // otherwise there is no need later to call the method continuously
    // Only generate one new random for each press of Space
    if (Input.GetKeyDown(KeyCode.Space))
    {
        GenerateRandom();
    }
}

public void GenerateRandom()
{
    // You only need a random index if you are actually gonna use it
    // Note I would get rid of the additional tags array and rather 
    // directly use the tags of given objects!
    // This way you can't mess them up and can easily add more
    int rnd = UnityEngine.Random.Range(0, veggies.Length);
    a =  veggies[rnd].tag;
    randName.text = a;
}

void OnCollisionEnter(Collision col)
{
    // Use the "a" stored in class scope not a parameter
    if (col.gameObject.CompareTag(a))
    {
        Debug.Log("Hit");

        // Little addition from my side
        // You could probably directly generate the next random after a match
        // so you wouldn't need the button and Update at all
        GenerateRandom();
    }
}

Вместо использования тегов вы могли бы также напрямую использовать ссылки на объекты и их имена:

GameObject a;

private void GenerateRandom()
{
    int rnd = UnityEngine.Random.Range(0, veggies.Length);
    a =  veggies[rnd];
    randName.text = a.name;
}

void OnCollisionEnter(Collision col)
{
    if (col.gameObject == a)
    {
        Debug.Log("Hit");

        GenerateRandom();
    }
}
...