Changing the Offset between Parent and Child

Hi there, I have an editor script which runs through all game objects with a specific tag and aligns them to a grid. All works well. The only fly in the ointment is that some objects have a parent and some don’t. Here’s the code:

	private void GatherAllObjects ()
		objectsInScene = GameObject.FindGameObjectsWithTag ("OBSTACLE");
		message = "Snapping " + objectsInScene.Length.ToString () + " objects";
		foreach (GameObject currentObject in objectsInScene) {
			// Some objects are parented, so check for a parent
			if ( currentObject.transform.parent == null )
				Debug.LogWarning(" has no PARENT. Snapping directly");
				//.. if no parent, snap object directly.
				currentObject.transform.position = SnapObjectToGrid (currentObject.transform.position);
		 		Debug.LogWarning(" has a PARENT "". Snapping parent and removing offset");

				//... and NOW send parent to be snapped to grid
				currentObject.transform.parent.position = SnapObjectToGrid ( currentObject.transform.parent.position );
				//.. Now change the offset between parent and child to 0,0,0 - DOESNT WORK!
			  	currentObject.transform.position = new Vector3 ( 0.0f, 0.0f, 0.0f );

The problem is in the else statement. If there is a parent, I snap the parent to the grid (which works fine) but then I want to ensure that there is no offset between the parent and child so I use the line:

currentObject.transform.position = new Vector3 ( 0.0f, 0.0f, 0.0f );

However, this doesn’t work and produces odd results (it gives the child similar x,y,z as the parent, but as an offset from the parent).

I’m clearly screwing this up - any ideas?

You want to use localPosition rather than position for the child position relative to it’s parent.

I think you’re looking for Transform.localPosition. This will set a position according to the transform of the parent, as opposed to the centre of the game world