shane
shane

Reputation: 342

Unity Moving Instantiated Objects

The code below works Except for the Instancated objects moving on their own. I want my Instancated objects to move back and fourth between pointA and pointB at a speed 0.5f.

Note: Im not trying to use the commented code in Start() and Update() because this file is attached to the camera.

With current code: My objectList objects are moving as expected just not their instantiated objects. I would like the Instantiated objects to move like ping-pong with their off-set

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

public class ObjectsSpawner : MonoBehaviour {

public GameObject[] objectList;
public  GameObject[] objectSpawns;
int val;

public float speed = 0.5f;
Vector3 pointA;
Vector3 pointB;

// Use this for initialization
void Start () {
    val = PlayerPrefs.GetInt("CannonPowerVal");
    addToList();
    for (int i = 1; i < objectSpawns.Length; i++){
        pointA = new Vector3(-3.8f, objectSpawns[i].transform.localPosition.y, 0);
        pointB = new Vector3(3.8f, objectSpawns[i].transform.localPosition.y, 0);
    }

    //pointA = new Vector3(-3.8f, transform.localPosition.y, 0);
    //pointB = new Vector3(3.8f, transform.localPosition.y, 0);

}

// Update is called once per frame
void Update()
{
    //PingPong between 0 and 1
    float time = Mathf.PingPong(Time.time * speed, 1);
    //transform.position = Vector3.Lerp(pointA, pointB, time);

    for (int i = 1; i < objectSpawns.Length; i++)
    {
        objectSpawns[i].transform.position = Vector3.Lerp(pointA, pointB, time);
    }
}

public void addToList(){
    objectSpawns = new GameObject[val];
    int max = objectList.Length;
    int counter = 8; // set first object out of screen sight

    // Adds Scene Objects from objectList to objectSpawns
    // Size of SceneObjects determined by CannonPowerVal

    for (int i = 0; i < PlayerPrefs.GetInt("CannonPowerVal"); i++){

        objectSpawns.SetValue(objectList[Random.Range(0, max)], i);
        // Random x spawn(-2.8f, 2.8f)
        Instantiate(objectSpawns[i], new Vector2(transform.localPosition.x + Random.Range(-2.8f,2.8f), transform.localPosition.y + counter), Quaternion.identity);

        counter = counter + 5;
    }
}

}

Upvotes: 0

Views: 1732

Answers (1)

The Knights of Unity
The Knights of Unity

Reputation: 46

after instantiating the object, you forgot to add the reference to the list of objectSpawns.

In addToList() method do:

GameObject object = Instantiate(objectSpawns[i],...);
objectSpawns.Add(object)

Upvotes: 2

Related Questions