如何将gameObject移至带有特定标签的随机对象

问题描述 投票:0回答:1

[嗨,我正在尝试弄清楚如何使对象移动到具有特定标签的另一个对象的位置。我目前有一个对象数组,其中包含该对象具有的所有“选择”。然后,我得到一个从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个回答
0
投票

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

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

public float choiceNumber;

如果将其更改为:

public int choiceNumber;

然后您的代码应该可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.