I am instantiating my gameobjects (spheres) through script. Now I want them to move from one place to some other every frame. I want my spheres move from one location to other. but I don’t know how to do this. Update is called once per frame. Is this worth doing? to do this all in an update function? or I know I can’t use OnGUI(), as it is just a liability. I am using unity free. I don’t want to use special plugins. My budget didn’t allows me.
The Update method is the right place to move objects. Don’t worry about performance before you have some hundred GameObjects moving, since it’s usually rendering that will kill the performance anyways, not simple scripts like this. Update is called as often as the game renders, whereas OnGUI for example gets called more often and you’d be moving the object more than once and then drawing it on the screen where it was left after the last move, which doesn’t make sense.
You could add a script like this to the objects you need to move.
If you want them to actually move every frame, delete all code except “moveToRandomSpot()” from inside update.
using UnityEngine;
public class Mover : MonoBehaviour
{
const float DELAY_MAX = 100f; // in seconds
const float DELAY_MIN = 10f;
const float POSITION_MIN = -100f; // in world units
const float POSITION_MAX = 100f;
private float _MoveDelay;
void Start()
{
setDelay();
}
void Update()
{
_MoveDelay -= Time.deltaTime;
if (_MoveDelay < 0)
{
moveToRandomSpot();
setDelay();
}
}
private void setDelay()
{
_MoveDelay = Random.Range(DELAY_MIN, DELAY_MAX);
}
private void moveToRandomSpot()
{
transform.position = new Vector3(Random.Range(POSITION_MIN, POSITION_MAX),
Random.Range(POSITION_MIN, POSITION_MAX),
Random.Range(POSITION_MIN, POSITION_MAX));
}
}