【问题标题】:How to move gameObject to a random object with specific tag如何将游戏对象移动到具有特定标签的随机对象
【发布时间】:2020-04-17 00:18:39
【问题描述】:

我试图弄清楚如何使一个对象移动到另一个具有特定标签的对象的位置。我目前有一个对象数组,其中包含对象拥有的所有“选择”。然后我得到一个从 0 到找到的对象数的随机数。我测试了这部分,它似乎运行良好。

我坚持的是将脚本所在的对象移动到脚本找到的对象的位置。我认为我需要做的是获取与索引号及其位置关联的对象,但这不起作用。提前致谢!抱歉,如果这个问题的结构不正确,这是我的第一篇文章!

public class objective : MonoBehaviour
{
    GameObject moveTo;
    public GameObject[] gameObjectChoices;
    public float choiceNumber;

    void Start()
    {
        //get objects with tag and apply it to object array
        gameObjectChoices = GameObject.FindGameObjectsWithTag("RandomCheesePoint");
        //choose one of the gameObjects in array
        choiceNumber = Random.Range(0, gameObjectChoices.Length);

        Debug.Log(choiceNumber);

        //move object to random object found
        transform.position = gameObjectChoices[choiceNumber].gameObject.transform.position;

        //problem occurs at gameObjectChoices[choiceNumber]
        //error message says "Cannot implicitly convert type 'float' to 'int' An explicit conversion exists (are you missing a cast?)"        
    }
}

【问题讨论】:

    标签: c# visual-studio unity3d


    【解决方案1】:

    您的问题是您尝试使用 float 值而不是 int 来索引数组。

    Random.Range() 将返回与其输入参数相同的类型(在您的情况下为 int),但此值将 implicitly cast 变为 float,因为您将变量声明为:

    public float choiceNumber;
    

    如果您将其更改为:

    public int choiceNumber;
    

    那么你的代码应该可以完美运行。

    【讨论】:

    • 非常感谢!就像你说的,效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多