Pose of Gameobject cannot be set in World coordinates
I wrote a function which is behaving very strangely. It takes as input arguments a Mesh and a Transform and is supposed to create a new GameObject, add the input mesh to it and places it at the same world coordinates as the input transform. Below is the code
using UnityEngine;
namespace CoreScripts
{
public class RayCastCollider : MonoBehaviour
{
private static void CreateHighlight(Mesh mesh, Transform originTransform)
{
string planeName = originTransform.gameObject.name;
var newPlane = new GameObject(planeName + "_highlight");
newPlane.AddComponent<MeshFilter>();
newPlane.AddComponent<MeshRenderer>();
var mf = newPlane.GetComponent<MeshFilter>();
mf.mesh = mesh;
var mr = newPlane.GetComponent<MeshRenderer>();
mr.material.shader = Shader.Find("Sprites/Default");
newPlane.transform.SetParent(null);
Vector3 p = originTransform.position;
Quaternion r = originTransform.rotation;
Debug.Log("Old plane position: " + p);
Debug.Log("Old plane rotation: " + r);
newPlane.transform.SetPositionAndRotation(p, r);
Debug.Log("New plane transformation position: " + newPlane.transform.position);
Debug.Log("Transform in World coordinate system: " + newPlane.transform.TransformPoint(newPlane.transform.position));
}
// Some other stuff
}
}
Now, I have generated a scene and created a simple plane object which I solely shift in z direction as shown in the picture below
Now I'm extracting the transform from this plane and pass it together with a simple plane mesh to the function CreateHighlight. However, when the function is finished, the new plane is not at the same world coordiantes as the original plane as shown in the picture below
The Debug output is:
Old plane position: (0,0,4.0) Old plane rotation: (0,0,0,1.0) New plane transformation position: (0,0,4) Transform in World coordinate system: (0,0,8)
It seems that the new plane is somehow refererencing the original plane as its world coordinate system. But how can that be, even when I've set the parent of its transform to null?