- Home /
Transform position check in update is slow
Hi
I'm making an infinite background that goes down along the Y-axis. Basically the background sprite transforms back to its initial position when it has reached the maxYposition that I've setup.
However my sprite background objects moves always way past the maxYPosition I've set up. Example: maxYPos = -5.6 but it snaps back to initial position when something like -6.6 is reached.
If I test my code in a new scene it works flawless.
What could be the reason my Update() responds so slow?
My C# code:
using UnityEngine;
using System.Collections;
public class MoveBuilding : MonoBehaviour {
public float backgroundMoveSpeed = 10f;
public double maxYPos;
private Vector3 startPos;
// Use this for initialization
void Start () {
startPos = transform.position;
}
// Update is called once per frame
void Update () {
//Moves object down
if(transform.position.y <= maxYPos){
transform.position = startPos;
}
transform.Translate(0, Time.deltaTime * -backgroundMoveSpeed, 0);
}
}
Check the prefab if it's a prefab, check the inspector settings to see if maxYPos was set to a value 1 lower. The fact that it's going a distance of exactly an extra 1 unit, is a bit telling of a coding or inspector change.
Also, perhaps try sticking it in LateUpdate().
Answer by Robacks · Feb 24, 2014 at 12:10 PM
Chache your transform component. Read this guide for detailed informations. I am used to make my own derived class of MonoBehaviour which overrides these shortcut getters, and caches those references when i do the first lookup with them.
$$anonymous$$ATE THAN$$anonymous$$ YOU. YOU ARE A GODSEND.
Answer by monserboy · Feb 24, 2014 at 01:09 PM
The answer of Robert Acksel solved it, along with teaching me a better way to program the transforms. Thank you very very much!!
Solution in C#, for future reference:
using UnityEngine;
using System.Collections;
public class MoveBuilding : MonoBehaviour {
public float backgroundMoveSpeed = 10f;
public double maxYPos;
private Vector3 startPos;
private Transform transformCache;
// Use this for initialization
void Start () {
startPos = transform.position;
}
void Awake () {
transformCache = transform;
}
// Update is called once per frame
void Update () {
//Moves object down
if(transformCache.position.y <= maxYPos){
transformCache.position = startPos;
}
transformCache.Translate(0, Time.deltaTime * -backgroundMoveSpeed, 0);
}
}
Your answer

Follow this Question
Related Questions
Rotate Method via Update ? 2 Answers
WebGL Run in Background only works 1 update per second 1 Answer
Make an Object Animate Up In The Update Function 2 Answers
Getting updated variables from another script 2 Answers
How do i Update a Transforms Position, and how do i have objects face along a spline?? 1 Answer