Unity 移动实例化对象

Unity Moving Instantiated Objects

除了实例化对象自行移动外,下面的代码有效。我希望我的实例化对象以 0.5f 的速度在点 A 和点 B 之间来回移动。

注意:我没有尝试在 Start() 和 Update() 中使用注释代码,因为此文件已附加到相机。

使用当前代码:我的 objectList 对象正在按预期移动,而不是它们的实例化对象。我希望实例化的对象像乒乓球一样移动,偏移量

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;
    }
}

}

实例化对象后,您忘记将引用添加到 objectSpawns 的列表中。

addToList()方法中做:

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