- Home /
Sprite is not shown moving
Alright, so I asked this question earlier, but I made some new discoveries about it that I think constitute a new question. I have a sprite that I am trying to move across the screen. Here is the script:
void Start()
{
database = GameObject.Find("DataBase");
if (database == null )
{
Debug.Log("DataBase not Found");
}
data dat = database.GetComponent<data>();
direction = dat.direct;
north = dat.NW.y;
west = dat.NW.x;
south = dat.SE.y;
east = dat.SE.x;
}
// Update is called once per frame
void FixedUpdate()
{
while (alive)
{
transform.position += direction * speed * Time.deltaTime;
if (transform.position.x <= west || transform.position.x >= east)
{
alive = false;
}
if (transform.position.y >= north || transform.position.y <= south)
{
alive = false;
}
Debug.Log("Transform Position: " + transform.position);
}
if (Input.GetButton("Jump"))
{
transform.position = new Vector3(11.0f, 0, 0);
alive = true;
}
}
The North South East and West are values which coordinate to the edges of the screen.
With the speed set to 0.1 on start the sprite will remain still for about 3 seconds before it "teleports" to the edge of the screen. My Debug.Log shows nothing in these 3 seconds, but when it teleports the console instantly shows 999+ debug messages claiming that the sprite was moving across the screen the entire time. The inspector shows no sign of the transform position changing at all apart from the starting point and the end point at the edge of the screen that it teleports to. I just don't understand what could be wrong. Any help would be appreciated.
Answer by mbro514 · Jul 04, 2020 at 06:11 PM
I think that your problem is that you're using a "while" loop. It's hard to explain why this is causing problems, but using an "if" loop or a Coroutine would work better for you.
Maybe this page from the Unity Manual can explain better:
Thank you so much! I just changed out the while for an if and it works fine. I looked through the Coroutine page too and I think I understand what was wrong which is much better than just finding out how to fix it.
Your answer
Follow this Question
Related Questions
Emerging Gap when moving my "Snake" 1 Answer
Question on Sprite and Movement 0 Answers
transform.position not doing anything 1 Answer