-1

I am trying to make simple terrain generation in my Minecraft clone. Whenever I try to run the script, it places ALL the instantiated objects at the position 0, 0, 0. Here is my C# code for terrain generation:

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 ()
    {

    }
bloobchube
  • 39
  • 10

3 Answers3

1

It looks like radius hasn't been set to a value yet, so your for loops are only running once.

Since x and z start at zero, and they're both only running once, the x and z position of the object are being set to zero.

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
  • Thanks, but no, that isn't the problem. In the Unity level editor window, I set the variable radius and max height to 20 and 1. – bloobchube Aug 06 '15 at 21:24
  • @bloobchube - use Debug.Log to check the values of z and x inside the loop. I think that they're zero, for one reason or another. – Pikamander2 Aug 06 '15 at 21:26
  • Pikamander2 I tried that. It logged that the wanted position and actual block position were both the same and that the block position was not at where it was in-game. – bloobchube Aug 06 '15 at 21:28
  • That sounds like a parenting problem to me. Does the block prefab have parents/children? – Reasurria Aug 07 '15 at 05:18
0

I'm sorry for all of the trouble I have been causing to all of you wonderful people. Of course, I was ignorant, and the problem was not with my terrain gen script, but with my block script!!!! I was constantly setting the position of the block and I was being very stupid. Thanks!

bloobchube
  • 39
  • 10
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.

Bestknighter
  • 111
  • 1
  • 2
  • 8