简体   繁体   中英

Script in C# is meant to move clouds in Unity but failed to work properly

I ran into this code in Unity that is meant to animate some clouds. It looks solid but it fails to move the object. Is there a possible error in the code? thank you for your time. I've been able write simple code to move objects back and forth but this code presented by Unity is a little out of my league. I would appreciate some feedback, thank you.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


namespace RPGM.Gameplay
{
/// <summary>
/// Performs batch translation of cloud transforms, resetting the transform position when
/// the cloud transform position exceeds the resetRadius distance to the controller.
/// Automatically collects and animates all it's child transforms.
/// </summary>
public class CloudSystem : MonoBehaviour
{
    public Vector3 windDirection = Vector2.right;
    public float windSpeed = 1;
    public float minSpeed = 0.5f;
    public float resetRadius = 100;
    Transform[] clouds;
    float[] speeds;


    void Start()
    {
        clouds = new Transform[transform.childCount];
        speeds = new float[transform.childCount];
        for (var i = 0; i < transform.childCount; i++)
        {
            clouds[i] = transform.GetChild(i);
            speeds[i] = Random.value;
        }
    }

    void Update()
    {
        var r2 = resetRadius * resetRadius;
        for (var i = 0; i < speeds.Length; i++)
        {
            var cloud = clouds[i];
            var speed = Mathf.Lerp(minSpeed, windSpeed, speeds[i]);
            cloud.position += windDirection * speed;
            if (cloud.localPosition.sqrMagnitude > r2)
            {
                cloud.position = -cloud.position;
            }
        }
    }

    void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, resetRadius);
    }
    }
    }

I suspect the problem is the clouds array is empty. That script is looking for its children, which presumably are clouds themselves. If it doesn't find any then it has nothing to act on. Make sure you put the cloud gameObjects as children of the game object with this script attached to it.

Another solution would be to expose the clouds array as a serializedfield and then you could drag clouds into it in the inspector rather than making them children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM