- Home /
Scene loading early problem with position script
Hello,
I am still fairly new to c# and unity, but I feel like this should be working fine. Here is my problem. I am trying to tell if an actor has moved, and if he has then I am changing scenes. However, everytime I push the play button, it automatically loads the next scene even if he doesn't move. Here is my code.
using UnityEngine;
using System.Collections;
public class CueBattle : MonoBehaviour {
Vector3 curposition;
Vector3 lastposition;
void start ()
{
curposition = new Vector3(transform.position.x, transform.position.y, transform.position.z) ;
lastposition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
}
void Update () {
curposition = transform.position;
if (curposition != lastposition)
{
Application.LoadLevel ("BattleGrass");
}
lastposition = curposition;
}
}
I am attatching this to my main actor who has a move script attatched to him, but he only moves when left right up or down is pressed. I am not pressing a key yet its still executing the Application.LoadLevel function. Any ideas what I'm doing wrong? Thanks for your time.
Found out that if I take out the line 16 curposition = transform.position; then it does not load next scene at all.
I tried it, and it still jumped me to the next scene immediately after I pushed play.
Try capitalising "Start", as well as changing the line if (curposition != lastposition)
to this:
if (curposition != lastposition && lastposition != null)
Additionally, it's good practice to capitalise the beginning of new words in your code variables.
Nope still didn't work. Is there maybe something that is moving it between line 12, lastposition = new Vector3(transform.position.x, transform.position.y, transform.position.z); and line 16 curposition = transform.position; ? I have a transform, sprite renderer, a rigidbody2d, a box collider 2d, and another script called movement will post it in a seperate comment.
Answer by RemoteBrainSoft · Jul 02, 2014 at 12:09 AM
Try this: using UnityEngine; using System.Collections;
public class CueBattle : MonoBehaviour
{
Vector3 lastposition;
void start ()
{
lastposition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
}
void Update () {
if (Vector3.Dot(lastposition, transform.position) > 0.01f) {
Application.LoadLevel ("BattleGrass");
}
lastposition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
}
}
This helps, but still does not work. It gives me maybe 1-3 frames that it stays on the main scene, but then loads the next scene before I press a key. It's close, or maybe there is a problem elsewhere.
It works now that I made another case. I said if one of x keys are pressed then do the stuff inside update, and it worked great. Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613152819im_/https://answers.unity.com/themes/thub/images/avi.jpg)