-1

What i want it to do is both in the editor and when running the game to see all the Spheres in the same time moving to another direction or maybe it will be the same direction untill endPoint and then back to the startPoint in a loop none stop.

This is my script:

using System;
using UnityEngine;
using Random = UnityEngine.Random;

[ExecuteInEditMode]
public class SphereBuilder : MonoBehaviour
{
    // for tracking properties change
    private Vector3 _extents;
    private int _sphereCount;
    private float _sphereSize;

    /// <summary>
    ///     How far to place spheres randomly.
    /// </summary>
    public Vector3 Extents;

    /// <summary>
    ///     How many spheres wanted.
    /// </summary>
    public int SphereCount;

    public float SphereSize;

    private void OnValidate()
    {
        // prevent wrong values to be entered
        Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
        SphereCount = Mathf.Max(0, SphereCount);
        SphereSize = Mathf.Max(0.0f, SphereSize);
    }

    private void Reset()
    {
        Extents = new Vector3(250.0f, 20.0f, 250.0f);
        SphereCount = 100;
        SphereSize = 20.0f;
    }

    private void Update()
    {
        UpdateSpheres();
    }

    private void UpdateSpheres()
    {
        if (Extents == _extents && SphereCount == _sphereCount && Mathf.Approximately(SphereSize, _sphereSize))
            return;

        // cleanup
        var spheres = GameObject.FindGameObjectsWithTag("Sphere");
        foreach (var t in spheres)
        {
            if (Application.isEditor)
            {
                DestroyImmediate (t);
            }
            else
            {
                Destroy(t);
            }
        }

        var withTag = GameObject.FindWithTag("Terrain");
        if (withTag == null)
            throw new InvalidOperationException("Terrain not found");

        for (var i = 0; i < SphereCount; i++)
        {
            var o = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            o.tag = "Sphere";
            o.transform.localScale = new Vector3(SphereSize, SphereSize, SphereSize);

            // get random position
            var x = Random.Range(-Extents.x, Extents.x);
            var y = Extents.y; // sphere altitude relative to terrain below
            var z = Random.Range(-Extents.z, Extents.z);

            // now send a ray down terrain to adjust Y according terrain below
            var height = 10000.0f; // should be higher than highest terrain altitude
            var origin = new Vector3(x, height, z);
            var ray = new Ray(origin, Vector3.down);
            RaycastHit hit;
            var maxDistance = 20000.0f;
            var nameToLayer = LayerMask.NameToLayer("Terrain");
            var layerMask = 1 << nameToLayer;
            if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
            {
                var distance = hit.distance;
                y = height - distance + y; // adjust
            }
            else
            {
                Debug.LogWarning("Terrain not hit, using default height !");
            }

            // place !
            o.transform.position = new Vector3(x, y, z);
        }

        _extents = Extents;
        _sphereCount = SphereCount;
        _sphereSize = SphereSize;
    }
}

Update

I created another c# script and dragged it to the Terrain.

using UnityEngine;
using System.Collections;

public class MoveSpheres : MonoBehaviour {

    public Transform _transform;
    private Vector3 pos1 = new Vector3(-4,0,0);
    private Vector3 pos2 = new Vector3(4,0,0);
    public float speed = 1.0f;
    // Use this for initialization
    void Start () {



    }

    // Update is called once per frame
    void Update () {

        _transform.position = Vector3.Lerp (pos1, pos2, Mathf.PingPong(Time.time*speed, 1.0f));


    }
}

This script move one Sphere. But i want to move all the Spheres. And also if i change in the first script the number of Spheres then move them too keep move them too.

The problem is with the Destroy part in the first script.

TheLost Lostit
  • 505
  • 6
  • 28
  • Other than the original questions there are a few code smells you want to to get rid of: is ``ExecuteInEditMode`` really necessary? Why search all objects (even based on their root name) when you can add a public variable? You can get all object transforms rather than the entire object (that said, it makes virtually no difference). Additionally you might want to attach a moving script on the object rather than doing all transforms in one loop (which the mono/unity compiler optimizes better for - also unity seems to get performance problems with very long loop times within one update of one obj – Mio Bambino Aug 30 '16 at 09:09

1 Answers1

0

you can lerp the spheres from one position to another and back https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

LumbusterTick
  • 1,067
  • 10
  • 21
  • It's working but only if i remove not using the destroy in the other script. The destroy just destry the sphere and make it missing transform in the new script. Even if i add a new gameobject sphere that is not connected to my other script. – TheLost Lostit Aug 30 '16 at 10:11
  • 1
    Ok relax , we can fix this but! One thing at a time , I want you to stop destroying the sphere for now . Tell me when do you want to destroy the sphere ? While its moving or when it has stopped moving? – LumbusterTick Aug 30 '16 at 10:41
  • Sorry. I want to destroy the Spheres only when i change the spheres count number. For example if i change the number of spheres to 1 destroy the other spheres and create 1 new. If i set then 10 spheres destroy the 1 and create new 10 spheres. This is the line DestroyImmediate (t); do in my script. But i have been told to use Destroy instead DestroyImmediate but Destroy not make what i want. – TheLost Lostit Aug 30 '16 at 11:02
  • Updated my question. Removed the MoveObjects function from the first script deleted the MoveObjects and created a new c# script file to make the moving. – TheLost Lostit Aug 30 '16 at 11:08
  • Ok cool now put the move script on the spheres that way when spehere is created it will move itself , now to delete and create new spheres , create an empty gameobject called spheres to delete all spheres use a for loop using gameobject.ChildCount to delete or make new spheres and set thier parent , hope it helps – LumbusterTick Aug 30 '16 at 11:15
  • I didn't understand yet how to make the destroy part. How can i destroy the Spheres each time changing the number of them without using DestroyImmediate. – TheLost Lostit Aug 30 '16 at 19:01
  • int i = 2; // number of spheres to destroy for(i – LumbusterTick Aug 31 '16 at 11:09
  • syntax can be wrong I cannot check ryt now but you will figure it out – LumbusterTick Aug 31 '16 at 11:10