Почему вы постоянно генерируете новое случайное значение, даже если вам нужно только одно внутри блока 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();
}
}