Hi all.
Im pretty new to unity, and i am working on a 2d platformer.
I am using portals to transform.position player to another position. I started up with hardcoding the new position in the script, but then i will have to a new script everytime i use a portal.
I need help to find a way to set the new location i the inspector (emty gameobject).
The script is attached to the portal.
This is what i use now
public class Transit : MonoBehaviour
{
private GameObject player;
private void Start()
{
player = GameObject.Find("Player");
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == ("Player"))
{
player.transform.position = new Vector3(-15.98f, 2.11f, 0);
}
}
}
The magic sauce you need is to obtain a reference to the Transform portal where you want the player to go, and to copy that Transform’s position to your player’s position.
Referencing variables, fields, methods (anything non-static) in other script instances:
REMEMBER: it isn’t always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.
Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.
That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.