I’m still a beginner when it comes to Unity. I have two objects which I can select and move. When I click one of the objects a square is highlighting it, indicating that it has been selected (see gif below).
The white square is its own game object, which get its position from the selected rectangles position. But when the rectangle move, the square lags. Why is this happening and how can I fix it? I don’t want to put the white square as a child object to the rectangles.

My code
I have three scripts:
- checks for clicking and if a clicked object is the rectangles. Assign to a special MouseController gameobject.
public class checkClick : MonoBehaviour {
Vector2 mousePos;
public GameObject selectedObject = null;
void Update () {
if (Input.GetMouseButtonUp (0)) {
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (mousePos, Vector2.zero);
if (hit.collider != null) {
selectedObject = hit.collider.gameObject;
} else {
selectedObject = null;
}
}
}
}
- The behaviour of the white border square. Assigned to the white square game object.
checkClick so;
void Start () {
so = checkClick.FindObjectOfType<checkClick> ();
}
void Update () {
//Debug.Log (so.selectedObject);
if (so.selectedObject != null) {
transform.position = so.selectedObject.transform.position;
GetComponent<Renderer>().enabled = true;
} else if (so.selectedObject == null){
GetComponent<Renderer>().enabled = false;
}
}
- Script for moving the rectangles. Assigned to the green/pink rectangles.
public float speed;
checkClick so;
Vector2 mousePos;
void Start () {
mousePos = new Vector3(transform.position.x, transform.position.y, 0);
so = checkClick.FindObjectOfType<checkClick> ();
}
void LateUpdate () {
if (Input.GetMouseButtonUp(1) && GameObject.ReferenceEquals( gameObject, so.selectedObject )) {
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if ( GameObject.ReferenceEquals( gameObject, so.selectedObject )){
transform.position = Vector2.MoveTowards(transform.position, mousePos, speed * Time.deltaTime);
}
}
Thank you!