Home > Mobile >  Make a GameObject stick to another GameObjects border in Unity
Make a GameObject stick to another GameObjects border in Unity

Time:02-24

I'm using Unity3D with MRTK for Hololens 2 development.

As you can see in the picture I gat a Square-Gameobject and a AppBar-Gameobject. The Square hast MRTK BoundsControl attached to it which make it transformable. The user can change the size and rotation of the Square with the handles.

The Scene is looking like this: Screenshot Scene

On every change the user does the AppBar should stick to the left border of the Square as shown in the screenshot.

The hierarchy of the prefab is: Screenshot hierarchy

The Object-Gameobject has a scale of: X: 1, Y: 1, Z: 1.
The Square-Gameobject has a scale of: X: 0.15, y: 0.15, Z: 0.009.

When I scale the Square with the handles only the scale of the Object changes the scale of the Square is staying the same all the time.

I already tried this code but it doesn't work properly:

using UnityEngine;

public class AppBar : MonoBehaviour
{
    public GameObject appBar;
    public GameObject MaterialObject;
    public void MoveAppBar()
    {

        var distance = MaterialObject.transform.localScale.x   MaterialObject.transform.GetChild(0).localScale.x - 1;
        appBar.transform.position = new Vector3(-distance - 0.032f, 0, 0);
    }
}

CodePudding user response:

It is by design. When changing the scale of the object, the child object under this object will deform visually, but the value of the scale property does not change.

The official Unity documentation clarifies this point: Parenting

Note that the Transform values in the Inspector for any child GameObject are displayed relative to the Parent’s Transform values.

CodePudding user response:

Add an empty object to the edge of the object that gets scale up/down. It needs to be on the edge so that when the main object gets modified, it will remain on the border.

Add this code to a script on the UI:

public Transform tr;
public float offset;
private void Update()
{
    Vector3 pos = tr.position;
    pos.x  = offset;
    transform.position = pos;
}

Drag the empty object to the tr slot and give a value to offset to indicate how far from that empty object you want the UI to remain.

Now you should be able to scale the main object and the UI will stick to that same distance from the edge without getting further or inside the main object.

A better approach would be to listen to the main object modification via event/listener so you don't run the update even when nothing happens.

  • Related