Search code examples
unity-game-engineunity3d-2dtools

Inconsistent floats with Unity


I have a couple prefabs I'm using to randomly generate a "room", but the same code is resulting in inconsistent widths:

Odd widths

The top (northWall) should be the same width as the bottom (southWall) but it's obviously 3 times the size.

Here is the "Room" prefab which instantiates the other "Wall" prefabs (they're all basically just Quads at this point).

public float length;
public float width;
public float wallDepth;

public Transform northWall;
public Transform southWall;

void Start () {
    length          = Random.Range (5.0f, 25.0f);
    width           = Random.Range (5.0f, 25.0f);
    wallDepth       = 2.0f;

    transform.localScale = new Vector3 (width, length, 0.0f);

    Instantiate (northWall, new Vector3(transform.localPosition.x, transform.localPosition.y + (transform.localScale.y / 2) + (wallDepth / 2), 10.0f), Quaternion.identity);
    northWall.transform.localScale = new Vector3 (width, wallDepth, 10.0f);

    Instantiate (southWall, new Vector3(transform.localPosition.x, transform.localPosition.y - (transform.localScale.y / 2) - (wallDepth / 2), 10.0f), Quaternion.identity);
    southWall.transform.localScale = new Vector3 (width, wallDepth, 10.0f);

}

Am I going crazy? Is it just late and I'm missing something?

Thanks.


Solution

  • I've solved the issue. I think it's due to the fact that I was using the same prefab for each of the four walls. I made a function which returns a clone of the prefab and reassigns it to the original quad. This way the scale and position transforms apply only to the copied version of the quad:

    GameObject buildWall (GameObject source, float width, float length, float x, float y, float z) {
        GameObject clone = Instantiate (source) as GameObject;
    
            clone.transform.localScale = new Vector3 (width, length, 0.0f);
            clone.transform.localPosition = new Vector3 (x, y, z);
    
        return clone;
    }
    

    And instantiation now looks like this:

    northWall = buildWall (northWall, width, wallDepth, transform.localPosition.x, transform.localPosition.y + (transform.localScale.y / 2) + (wallDepth / 2), 10.0f);
    

    I don't know if this is the most effective (or even correct) way to go about doing this, but it seems to work for now.