2D game objects are moving even when I am not in the scene.
I have a script that moves a game object across the screen like an auto scroller background. But, the objects start moving even when the scene is not loaded, i tried using an OnSceneLoaded but it still didn't fix the issue. I assume it is something with the update calling out of scene but i am not sure how to fix it.
public class Scroller : MonoBehaviour
{
public float scrollSpeed;
public float tileSizeZ;
private Vector2 startPosition;
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
Debug.Log("Script Was Enabled");
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
startPosition = transform.position;
Debug.Log("LevelOne loaded");
}
private void Update()
{
float newPosition = Mathf.Repeat(scrollSpeed * Time.time, tileSizeZ);
transform.position = startPosition + Vector2.left * scrollSpeed;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
}
Scenes are just collections of GameObjects that are loaded in at once. GameObjects are bound to their scenes in a way and will be cleared if the scene is changed -- assu$$anonymous$$g you haven't flagged them to be preserved -- but I don't think that there's some weird out-of-scene behavior going on here.
Looking at your code, I'm not sure what you're trying to do. It's a scroller from the name, but you're not using newPosition
at all. Your transform.position
will always be the same as a result because you're multiplying it by two things that are probably constant most of the time (unless scrollSpeed
is how you're moving the scene?).
Did you mean to use something like this?
transform.position = transform.position + Vector2.left * Time.deltaTime;
Your answer
Follow this Question
Related Questions
Can someone tell me how to restart the scene if my player hits two objects 2 Answers
What is the most effective way to structure Card Effects in a Single Player game? 1 Answer
Multiple Sprites, One Script, Randomization 1 Answer
Any one help me in this script? 0 Answers
Ball Rotate Around Cube 1 Answer