2D character Teleport when clicking sprite

Hi I am trying to figure out how I can have the player teleport to a location (100,100) when I click a Box Collider on a sprite (the sprite is called “tp_door” and the player is called “player”). I am fairly new to unity and have spent the past few days trying to figure this out.

What you’re trying to do is a very common task in Unity. You have a component (the script on your Sprite), which needs to change the position of a different GameObject. Communications between components and gameobjects is in just about every game you will ever create. The simplest way is this:

In your sprite script, put [SerializedField] Transform playerTransform; on the line following the class definition.

At the point in your code where you want to do the transform, write playerTransform.position = new(100, 100, 0); Save your code.

Go back to Unity and in the Inspector for the Sprite, find the script component. It should now have a field with “Player Transform” to the left. Drag the player from the hierarchy into that field.

What you’ve done is to set up addressability between the Sprite Script and the Player, so that the Script can see and manipulate the Player directly.

By the way, this is not really considered the best practice (though it is simple) because you might argue that it’s not the job of one component to move another. For example, if there was also to be an animation, some audio and perhaps stopping an existing animation, turning off keyboard input while the teleport was taking place and all sorts of other activities, your sprite code would definitely be doing work for which it should not have responsibility. In the long run, you should learn about Events, which are the best way of handling something like this. For now, go with what I’ve suggested above.