Why does my script lose track of my character every time I hit play?
I'm trying to make doors for my game but every time I hit play it losses track of my player. How do I fix this?
This is the script that i'm using:
public string scene;
public GameObject player;
public Vector2 newPos;
private void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
private void OnTriggerStay2D(Collider2D collision)
{
if (Input.GetKeyDown("e"))
{
player.transform.position = newPos;
SceneManager.LoadScene(scene);
Debug.Log("Change");
}
}
}
Answer by IgnitedGames · May 09, 2020 at 03:15 AM
So this script hasn't been able to find the player at all, or has it worked before? I haven't used GameObject.FindGameObjectWithTag before but from reading the documentation I think it's meant to return an array of every GameObject with that tag. I'd strongly suggest (assuming you are only meant to have one player) using GameObject.FindWithTag instead and making sure only one GameObject has this tag. Try this:
public string scene;
public GameObject player;
public Vector2 newPos;
private void Start()
{
player = GameObject.FindWithTag("Player");
}
private void OnTriggerStay2D(Collider2D collision)
{
if (Input.GetKeyDown("e"))
{
player.transform.position = newPos;
SceneManager.LoadScene(scene);
Debug.Log("Change");
}
}
Answer by judahwilliams1211 · May 09, 2020 at 06:12 PM
IT WORKED!!! Thank you so much!!!
All good, if you want you can accept my response so people looking for a solution to this problem can know that there is a solution in this post
Your answer
![](https://koobas.hobune.stream/wayback/20220612233719im_/https://answers.unity.com/themes/thub/images/avi.jpg)