Search Unity

Parent object grid system troubles

Discussion in 'Scripting' started by Thimble2600, Nov 27, 2015.

  1. Thimble2600

    Thimble2600

    Joined:
    Nov 27, 2015
    Posts:
    165
    Hello there,

    I'm setting up a grid system object. I make an empty GameObject with the following script.
    It gets an array of all child GameObject and transforms their positions to align in an 8 by 8 grid, it snaps to the nearest multiple of 8.

    Code (CSharp):
    1. [ExecuteInEditMode]
    2. public class Grid : MonoBehaviour {
    3.  
    4.     void Update () {
    5.  
    6.         Transform[] childObjects = transform.GetComponentsInChildren<Transform>();
    7.        
    8.         foreach (Transform item in childObjects)
    9.         {
    10.             float x = Mathf.Round(item.transform.position.x / 8) * 8;
    11.             float y = Mathf.Round(item.transform.position.y / 8) * 8;
    12.  
    13.             item.transform.position = new Vector3(x, y, 0.0f);
    14.         }
    15.     }
    16. }
    This works just fine and dandy, however I'm finding that the GameObject that uses this Grid script component is also snapping to grid and I can't figure out why, as the script Gets the transform component of it's children, and not itself.

    I hope I've explained this clearly, thanks for your time :)
     
  2. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,261
    I believe that it also grabs the component from the GO you call it on with GetComponentsInChildren().

    Putting an if to stop it from doing it to the parent should work

    Code (CSharp):
    1. if (item == transform)
    2.     continue;
    You could also change it to this

    Code (CSharp):
    1. foreach (Transform child in transform)
    2. {
    3.     //Do your thing here
    4. }
     
  3. LukePammant

    LukePammant

    Joined:
    Mar 10, 2015
    Posts:
    50
    The GetComponentsInChildren method actually does look inside the current GameObject for the component as well. Here is a quote taken from the summary comment in the GetComponentsInChildren method:
    If you load the transforms into a List<Transform> you could just do this right after your GetComponentsInChildren call:
    Code (CSharp):
    1. childObjects.Remove(transform);
    This will fail silently if it doesn't exist in the List.