I want to move a parent object while “holding” its child. I am trying to write a tool for Editor. Therefore, my script is marked with the [ExecuteInEditMode] attribute. But the attribute is only indirectly related to the question.
The direct solution is this:
[ExecuteInEditMode]
public class MoveController : MonoBehavior
{
[SerializeField] private Transform _child;
private void Update()
{
transform.position = _child.position;
}
}
It has been accepted as an answer here: https://forum.unity.com/threads/moving-parent-with-child-component.502310/
However, the last comment clearly describes the problem with a solution like this:
if we move the child … at a constant
speed … then the child will continue
to accelerate off screen
I’m moving the child element with the Move tool (“arrows”). But I get exactly the same result. Obviously, when the parent is moved, a new movement of the child also occurs. It is added to the original movement. This leads to a rapid and uncontrolled increase in the speed of movement.
I assumed that a offset is required. It must be taken into account when moving. A similar method has been discussed here: How to move parent when child moves? - Questions & Answers - Unity Discussions
But the accepted answer essentially leaves the parent in its place:
transform.parent.position = transform.position - transform.localpostion;
I thought I needed a local offset. I wrote this code:
private void Update()
{
Vector3 delta = _child.localPosition - _oldChildLocalPosition;
_child.position -= delta;
transform.position += delta;
_oldChildLocalPosition = _child.localPosition;
}
However, the result is about the same. The parent speeds up unpredictably when the child is moved. Did I make a stupid mistake somewhere? Or am I missing some important non-obvious detail?