坚持将随机生成的字符串与游戏对象 name/tag 进行比较?

Stuck with comparing an random generated string with game object name/tag?

开发一个小游戏,其中将生成随机名称并显示在文本 space 中,玩家应与文本 space 中显示的名称的对象发生碰撞。例如,如果显示“柠檬”,那么玩家应该触摸放置在 table.

上的柠檬游戏对象
   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");
            }
        }
    
    }

为什么你不断地生成一个新的随机值,即使你只需要 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();
    }
}