Parenting and ScreenToWorldPoint() wackiness

This code tries to make a slider relative to a menu item’s position…

	public void MakeSlider (Setting param, GameObject menuHolder) {
		slider = new GameObject ("Slider");
		if (openMenu.localised) {
			slider.transform.parent = menuHolder;
			slider.transform.localPosition = param.slider.pos + Delocalise (menuHolder.transform.position);
			param.slider.bar.localised = true;
			param.slider.hand.localised = true;
		}
		slider.transform.localRotation = Quaternion.Euler (param.slider.rot);
		slider.transform.localScale = param.slider.scale;
    //[...]
	}

…using this custom function…

public Vector3 Delocalise (Vector3 pos) {
	pos = new Vector3 (Camera.main.ScreenToWorldPoint(pos).x / Screen.width,
	                   Camera.main.ScreenToWorldPoint(pos).y / Screen.height,
	                   pos.z);
	return pos;
}

…where menuHolder is an empty parent GameObject, itself a child of the empty menu parent GameObject. The menu applies a position to menuHolder, which in turn applies a position to a GUIText menu item. The idea is to have not a GUITexture, but two groups of animated GameObjects with Sprite Renderer components to make up the slider at runtime.

Everything seems to work perfectly except for the conversion from screen units to world units that would make the slider relative to the menu item. I’ve tried not dividing by screen width and height and the results are different, but still unsatisfactory.

It seems as though Delocalise is taking menuHolder’s local position instead of its global position like transform.position should.

This might not be the answer you’re looking for but I have a few suggestions to solve your problem:

  1. Screen.width and Screen.height are integers. Your calculation will often be imprecise without casting these.
  2. ScreenToWorldPoint z coordinate is tricky. This should not be the actual z coordinate of the position you want to delocalise. This should be how far into the world from the camera to go.

So if your camera is looking down the Z axis, you’d use something like -5 or -10 or however far your camera is from the spot in the world you’d like to convert your coordinates to.

Or if you are not that far into the project, may I suggest to upgrade to Unity 4.6 beta. The new GUI tools makes life so much easier! I just switched my project which was halfway done and it took me around a day and half worth of work, but now I can create the GUI way too fast. I know I have saved at least 3-4 days worth of work in future, so it was a good tread-off for me.