I’m trying to balance learning with productivity right now and am having great success finding most of what I need, but cannot find this basic script!
I have some 3D clouds - simple mesh objects - that I’d like to move through the sky at a constant speed.
Would someone be kind enough to write a simple script (public variables would be awesome) to move them along the Z axis? (This is for a 3 minute cutscene, so there’s no need to repopulate or be concerned about the clouds eventually disappearing. I just need them to move very slowly to add life to the scene.)
And again in C#. This shows the entire class (ie everything that needs to be in the file). Assign speed in the inspector.
using UnityEngine;
using System.Collections;
public class MoveScript : MonoBehaviour {
public float speed;
void Update() {
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
}
function Update() {
// Move the object forward along its z axis 1 unit/second.
transform.Translate(Vector3.forward * Time.deltaTime);
// Move the object upward in world space 1 unit/second.
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
There are no global variables in C# like in line 4:
public float speed;
The use of public modifier hints you there is something wrong here: make no sens to make a global variable public - after all what does it even mean for a global variable to be private?
This variable should be a field of your MoveScript class. This will fix the error.
Tip: It’s a bad practice to have public fields in general. Better way to expose a field in inspector is to use the SerializeField attribute ( Unity - Scripting API: SerializeField ):
using UnityEngine;
using System.Collections;
public class MoveScript : MonoBehaviour {
[SerializeField]
private float speed;
void Update() {
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
}