Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How can i let the player move between areas/scenes?

Discussion in '2D' started by Frankthemonke, Oct 13, 2019.

  1. Frankthemonke

    Frankthemonke

    Joined:
    Oct 13, 2019
    Posts:
    1
    I want the player to move between areas/scenes but i wrote a script i got an error saying: Script Error: OnTriggerEnter2D This message parameter has to be of type: Collider2D.
    I don't know how to fix this, so it would be really helpful if someone could help.

    Here is the script:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.SceneManagement;


    public class LoadNewArea : MonoBehaviour
    {

    public string levelToLoad;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter2D(Collider2D other)
    {
    if (other.gameObject == "Player")
    {
    SceneManager.LoadScene(levelToLoad);
    }
    }
    }

    I'm sorry if it is a really dumb mistake, i'm new to game developing so i don't know much yet about programming.
     
  2. Dark777Soul

    Dark777Soul

    Joined:
    Feb 9, 2017
    Posts:
    1
    If you identify a player by tag
    Code (CSharp):
    1. void OnTriggerEnter2D(Collider2D other)
    2. {
    3. if (other.gameObject.tag == "Player")
    4. {
    5. SceneManager.LoadScene(levelToLoad);
    6. }
    7. }
    But if by GameObject name, necessary to replace "tag" to "name".
    I hope that helped.
     
  3. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    You could use PlayerPrefs to store your player's Vector3 Transform.position, so when you transition scenes you can access that information anyhow you'd like to use it.

    Code (CSharp):
    1. [SerializeField]private Transform playerTrans; // You add your player game object in this field
    2. private Vector3 playerPos;
    3.  
    4. private void Update()
    5. {
    6. playerTrans = playerTrans.position;
    7. playerPos = Vector3(playerTrans.position.x, playerTrans.position.y, playerTrans.position.z);
    8. PlayerPrefs.SetFloat("PlayerPosition", playerPos);
    9. }
    This isn't the most efficient or practical way to call this. You should design a function and have it call only when you need to. I just wrote a quick example.

    This is untested so there's a chance you may need to do this:
    Code (CSharp):
    1. playerPos = new Vector3(playerTrans.position.x, playerTrans.position.y, playerTrans.position.z);
    2. // Adding the NEW keyword may be required or perhaps be better?