Moving a spawned object in a direction
Hey All,
So I've got a script that spawns clouds from prefabs at random locations, I'm trying to get them so they move in a direction (as clouds do) however I can't seem to get it to work.
public Transform cloud;
public float cloudSpeed = 1;
// Use this for initialization
void Start() {
// Spawn clouds across sky
System.Random ran = new System.Random();
int xValue = ran.Next(90, 100);
for (int y = 0; y < 7; y++) {
for (int x = 0; x < 7; x++) {
Instantiate(cloud, new Vector3(ran.Next(-280, 280), ran.Next(80, 100), ran.Next(-270, 270)), Quaternion.identity);
}
}
// Update is called once per frame
void Update () {
cloud.transform.Translate(cloud.transform.forward * cloudSpeed * Time.deltaTime);
}
If I remove "cloud." from that second to last line ("cloud.transform.Translate(cloud.tra...) and it moved the object the script is attached to.
Any help would be greatly appreciated and apologies if this is a noob question, I've tried the docs too.
Thanks!
Answer by Jawchewa · Aug 11, 2017 at 02:13 AM
What are you setting your cloud speed to? If it's just 1, then this problem would make sense, as multiplying by delta time makes the number significantly smaller. Maybe try increasing that number, and see if it helps.
Also, It doesn't look like you are ever actually storing a value for your cloud variable, so at that point in the update, cloud is most likely null. You would have to fix that by doing something like this:
cloud = Instantiate(cloud, new Vector3(ran.Next(-280, 280), ran.Next(80, 100), ran.Next(-270, 270)), Quaternion.identity);
Or, since it looks like you are planning on having multiple clouds, you probably want to change how you are storing your object to a list of Transforms, instead of just a single one. That would look something like this:
List<Transform> clouds = new List<Transform>();
clouds.Add(Instantiate(cloud, new Vector3(ran.Next(-280, 280), ran.Next(80, 100), ran.Next(-270, 270)), Quaternion.identity));
And then loop through each of the clouds in the update.