Search Unity

Place GameObjects with even horizontal distribution

Discussion in 'Scripting' started by Geo-Ego, Apr 4, 2017.

  1. Geo-Ego

    Geo-Ego

    Joined:
    Sep 25, 2012
    Posts:
    12
    I'm looking to place an arbitrary number of GameObjects evenly across an arbitrary width. I've got something close but it isn't quite right.

    Code (csharp):
    1.  
    2.             float newSpacing = rowWidth / (numberOfBlocks + 1);
    3.  
    4.             for (int i = 0; i < numberOfBlocks; i++)
    5.             {
    6.                     GameObject newBlock = (GameObject)Instantiate(blockTemplate, this.gameObject.transform.position, Quaternion.identity);
    7.                     newBlock.transform.parent = this.gameObject.transform;
    8.  
    9.                     float newXPosition = (rowWidth / 2) - (newSpacing * i) - this.gameObject.transform.localScale.x;
    10.                     newBlock.transform.localPosition = new Vector3(newXPosition, 0, 0);
    11.             }
    12.  
    What I am attempting there is to first calculate the spacing based on the number of objects I want and the overall width, then place the objects accordingly. I'm finding that while they are spaced evenly, but they're not centered inside the expected width. What am I missing?
     
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    I think the issue is that the center point of blockTemplate. you need to know the width of this object. and add half it's width to the x position.

    attach a screen shot so we can see what it's doing wrong
     
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    In addition to the previous poster's feedback, an observation I made is that you are subtracting localScale.x and I don't think that that applicable here. Since localScale is a proportional value..In closing, I believe your scenario wouldn't need to factor the scaling at all, at first glance.