Hello, so I’m just starting to learn C#, and I try to make my player move to another location with a click. But I dont understand why my code is not working. Could anyone help me ?
Thanks
teleporter code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleporter : MonoBehaviour
{
[SerializeField] private Transform destination;
public Transform GetDestination()
{
return destination;
}
}
Player Teleporter code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTP : MonoBehaviour
{
private GameObject currentTeleporter;
void Update()
{
if(Input.GetKeyDown(KeyCode.E))
{
if(currentTeleporter != null)
{
transform.position = currentTeleporter.GetComponent<Teleporter>().GetDestination().position;
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Teleporter"))
{
currentTeleporter = collision.gameObject;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Teleporter"))
{
if (collision.gameObject == currentTeleporter)
{
currentTeleporter = null;
}
}
}
}
Make sure your colliders are BoxCollider2D. The teleport colliders should be set to trigger. Add some Debug.Log() statements to your code to see what is happening at various points.
– ArachnidAnimal