I have a room that I want to connect to a staircase. Both the room and the stairs have the following parameters:

enter image description here

I need to "magnet" the "Room Exit" position of the room (start room) to the "Room Entry" staircase. The staircase itself, I create through Instantiate

How can i do this?

New contributor
ArtemiZ Studio is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • 1
    \$\begingroup\$ Are you saying you don't know how to position GameObjects from code? Have you tried a web search? \$\endgroup\$ – Kevin Feb 19 at 1:01

If I understand you correctly, you have two objects that contain entry and exit points. The entry/exit points are each marked by the location of a specific child object transform inside those parents. You want to find a position to place one of these parent objects so its entry child exactly matches the position of the other parent object's exit child.

If so, you can do that like this:

void SnapParentToAnchor(Transform anchor, Transform parentToMove, Transform childToAlign) {
    // Get the position in the world of the fixed child we want to align to.
    Vector3 worldPosition = anchor.position;

    // Get the world space offset of the matching child from its parent.
    var offset = parentToMove.TransformVector(childToAlign.localPosition);

    // Form a world position for the parent that will put this offset exactly at our anchor.
    parent.position = worldPosition - offset;

You can use this to fix-up the position of the parent after you've instantiated it with the rotation and scale you want.

Or, if you're not rotating/scaling these objects, you could change this method to return the Vector3 position = worldPosition - offset to use. Then call it with the prefab parent/child to get that vector, and pass it to Instantiate(prefab, position, rotation) to instantiate it in-place in one go.

  • \$\begingroup\$ Thank you so much, thats work perfect. \$\endgroup\$ – ArtemiZ Studio yesterday

Your Answer

ArtemiZ Studio is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.