Search code examples
c#unity-game-enginehololensmrtk

Make a GameObject stick to another GameObjects border in Unity


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.

On every change the user does the AppBar should stick to the left border of the Square.

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);
    }
}

Solution

  • 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.