Unity对象始终在0,0,0处实例化

时间:2015-08-06 21:17:43

标签: c# object unity3d instantiation gameobject

我正在尝试在我的Minecraft克隆中生成简单的地形。每当我尝试运行脚本时,它会将所有实例化对象放在0,0,0位置。这是我生成地形的C#代码:

using UnityEngine;
using System.Collections;

public class TerrainGen : MonoBehaviour {

    public int radius;
    public int maxHeight;

    public GameObject block;

    void Start ()
    {
        for (float x = 0; x < radius; x+=1)
        {
            for (float z = 0; z < radius; z+=1)
            {
                float y = Random.Range(1, maxHeight);
                Vector3 v = new Vector3(x, y, z);
                GameObject newBlock = Instantiate(block, v, Quaternion.identity) as GameObject;
                Debug.Log("Block's Position: " + newBlock.transform.position + " | Wanted Position: " + v);
            }
        }
    }

    void Update ()
    {

    }

3 个答案:

答案 0 :(得分:1)

看起来radius尚未设置为某个值,因此您的for循环只运行一次。

由于xz从零开始,并且它们都只运行一次,因此对象的xz位置被设置为零。

答案 1 :(得分:0)

对不起我给你所有人带来的所有麻烦。当然,我是无知的,问题不是我的地形gen脚本,而是我的块脚本!我经常设置块的位置,我非常愚蠢。谢谢!

答案 2 :(得分:0)

Try doing this:

GameObject newBlock = Instantiate(block, v, Quaternion.identity) as GameObject;
newBlock.transform.position = v;

I don't know if this will fix your problem, and I don't know either if it's a bug with the instantiate method or if it's a misunderstanding by us, but everytime I try to instantiate an UI element, I need to reset the position (and the scale) in the same way as above. Never tried with a cube, but with UI it does the job.