为什么向量没有延续到其他函数中?



当我将向量分配给数组时,将不会传递到rocketUpdate函数。正在使用的Gene数组来自于在火箭数组的gameObjects上运行的另一个脚本。这就是它的脚本。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rockets : MonoBehaviour {
public Vector2[] Gene;
public void Start()
{
Gene = new Vector2[10];
}
}

这是主"控制器"脚本。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RocketController : MonoBehaviour {
public int XVelocityMultiplier;
public int YVelocityMultiplier;
int lifespanSec;
int Count;
public int Size;
public GameObject[] rockets;
public GameObject RocketPrefab;
public System.Random rnd = new System.Random();
float x;
float y;
void Start()
{
rockets = new GameObject[Size];
lifespanSec = RocketPrefab.GetComponent<Rockets>().Gene.Length;
Invoke("killRockets", lifespanSec);
for (int i = 0; i < rockets.Length; i++)
{
GameObject rocketObject = Instantiate(RocketPrefab);
rocketObject.GetComponent<Rigidbody>().position = new Vector3(0, -4, 30);
rocketObject.name = "Rocket_" + (i+1);
for (int j = 0; j < rocketObject.GetComponent<Rockets>().Gene.Length; j++)
{
x = Convert.ToSingle(rnd.NextDouble() * (2 * XVelocityMultiplier) + XVelocityMultiplier * (rnd.Next(-1,1) + 0.1f));
y = Convert.ToSingle(rnd.NextDouble() * (YVelocityMultiplier));
rocketObject.GetComponent<Rockets>().Gene[j] = new Vector2(x, y);
Debug.Log(rocketObject.GetComponent<Rockets>().Gene[j]);
}
rockets[i] = rocketObject;
}
InvokeRepeating("RocketUpdate", 0, 1);
}
void Update()
{
if (Count == lifespanSec)
{
Count = 0;
}
}
void RocketUpdate()
{
Debug.Log(rockets[1].GetComponent<Rockets>().Gene[Count]);
if (rockets[0] != null)
{
for (int i = 0; i < rockets.Length; i++)
{
rockets[i].GetComponent<Rigidbody>().velocity = rockets[i].GetComponent<Rockets>().Gene[Count];
}
Debug.Log(rockets[1].GetComponent<Rockets>().Gene[Count]);
}
Debug.Log(Count);
Count++;
}
void killRockets()
{
for(int i = 0; i < rockets.Length; i++)
{
Destroy(rockets[i]);
}
}
}

当我在start函数中运行第一个Debug.log((时,每个gameObject都有它的值。但当我在rocketUpdate((中运行相同的Debug.log时,它突然不再有值了。我在同一个问题上纠结了很长时间。如果有人知道这个问题,请告诉我。

几件事。在第一个脚本中,您没有用一堆值填充数组,而是创建了一个新的数组,其中包含10个Vector2s的空间。我不确定这是否是你想要的,但这就是它。为了用数据填充它,你必须通过创建对包含实际值的脚本的引用来明确地告诉它数据应该是什么。例如,

private MainScript whateverYouWannaCallIt;
private Vector2[] geneCopies; 
public void Awake()
{
whateverYouWannaCallIt = gameObject.GetComponent<MainScript>();
for (int i = 0; i < whateverYouWannaCallIt.rockets.Length; i++)
{
geneCopies[i] = whateverYouWannaCallIt.rockets.gene[i];
}
}

您还应该初始化一个List,并用这些火箭填充它,也许还有一个用于刚体的火箭,这些getComponent调用将大大增加您的开销。

此外,我很感兴趣。这个脚本的目标是什么?你的游戏是关于什么的?

最新更新