创建三维网格两个元素,一行中有一个元素,但是在随机列中

时间:2014-07-28 03:31:05

标签: c# list unity3d

我创建了一个三维网格。我有两个单独的对象填充此网格的空间。我希望在一行中有一个对象,但是在随机选择的列上。

以前是否有人这样做过,或者有人能指出我正确的方向吗?

我正在使用Unity和C#。谢谢。

    Vector3 towerSize = new Vector3(3, 3, 3);

//create grid tower
for (int x = 0; x < towerSize.x; x++)
{
    for (int z = 0; z < towerSize.z; z++)
    {
        for (int y = 0; y < towerSize.y; y++)
        {
            //spawn tiles and space them
            GameObject obj = (GameObject)Instantiate(tiles);
            obj.transform.position = new Vector3(x * 1.2f, y * 1.2f, z * 1.2f);

            //add them all to a List
            allTiles.Add(obj);
            obj.name = "tile " + allTiles.Count;
        }
    }
}

网格的代码。我试图让单个List中的两个对象移动到那些tile,但是当我使用这段代码时,随机列对象会进入相同的列:

for (int i = 0; i < allCubes.Count; i++)
{
    allCubes[i].transform.position = Vector3.MoveTowards(
        allCubes[i].transform.position,
        allTiles[i].transform.position, 10 * Time.deltaTime);
}

然后想到将两种类型的立方体放在单独的列表中。最终变得更加混乱。哈哈发布该代码有帮助吗?

1 个答案:

答案 0 :(得分:0)

我知道这是我的一个非常古老的问题。这个项目被取消了。我随机碰到了它,出于好奇,我决定尝试完成这个特殊的问题,当时我遇到了这样的麻烦。我做到了。

public Vector3 towerSize = new Vector3(3, 3, 3);

    public GameObject tiles;
    public GameObject randomTile;

//public variables for debugging purposes.
//no real need to be seen in inspector in final.  cleaner too if they're hidden
    public int randomSelectedTile;

    public List<GameObject> allTiles;

    void Start()
    {
        //create grid tower
        for (int x = 0; x < towerSize.x; x++)
        {
            for (int z = 0; z < towerSize.z; z++)
            {
                for (int y = 0; y < towerSize.y; y++)
                {
                    //spawn cubes and space them
                    GameObject obj = (GameObject)Instantiate(tiles);
                    obj.transform.position = new Vector3(x * 1.2f, y * 1.2f, z * 1.2f);

                    //add them all to a List
                    allTiles.Add(obj);
                    obj.name = "tile " + allTiles.Count;
                }
            }
        }

        //select a random cube in the list
        randomSelectedTile = Random.Range(0, allTiles.Count);

        //get the cube object to delete
        GameObject deleteObj = allTiles.ElementAt(randomSelectedTile);
        //spawn the random cube at the position of the cube we will delete
        GameObject rndObj = (GameObject)Instantiate(randomTile);
        rndObj.transform.position = deleteObj.transform.position;

        //remove the element at that location
        allTiles.RemoveAt(randomSelectedTile);
        //insert the random cube at that element's location
        allTiles.Insert(randomSelectedTile, rndObj);

        //destroy the unwanted cube
        Destroy(deleteObj);
    }

很高兴看到你如何随着时间的推移而改善。以防万一其他人从解决方案中受益。再次,我为重新启动而道歉。