Having issue snapping a gameobject to a transform

Hi there,

Would somebody be able to tell me why this doesn’t work?

public void OnTriggerEnter2D(Collider2D col)
{
    if (col.tag == "Grid")
    {
        Debug.Log("Creature has been snapped");
        transform.position = col.gameObject.transform.localPosition;
    }
}

I’m trying to move the gameObject this script is attached to to the transform.position of the gameobject the collider ‘col’ is attached to.

The intended behaviour is that you drag the gameobject inside a trigger with your mouse and then it snaps to the center of the gameobject the trigger is attached to.

The Debug.Log triggers here but the “transform.position = col.gameObject.transform.localPosition;” line is doing nothing.

Any help would be appreciated. Thank you.

Probably because you have a bug: something isn’t executing, it’s connected to the wrong object, whatever normal type of bug you have going on.

Time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

If you find out more and things are still mysterious, try this checklist:

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?

You don’t show how you’re moving the object but if you’re setting its position to the mouse position then the changes OnTriggerEnter2D makes will be immediately replaced with your mouse moving code. Or if you’re moving the object by adding the mouse delta to its position then OnTriggerStay2D may be better suited.

Also, line 6 should probably be:

transform.position = col.transform.position;