【发布时间】:2018-11-26 10:13:19
【问题描述】:
当我将向量分配给数组时,不会将其传递给 RocketUpdate 函数。正在使用的基因阵列来自在火箭阵列的游戏对象上运行的其他脚本。这是它的脚本。
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]);
}
}
}
当我在启动函数中运行第一个 Debug.log() 时,每个游戏对象都有它的值。但是当我在 RocketUpdate() 中运行相同的 Debug.log 时,它突然不再具有它的值。很长一段时间以来,我一直被同一个问题困扰。如果有人知道问题,请告诉。
【问题讨论】:
-
附注:一般情况下尽量避免一遍又一遍地调用
GetComponent。而是在第一次获得参考后存储并重复使用它。你可以例如已经制作了Rockets[]类型的rockets,或者为什么不使用List<Rocket>()?列表的巨大优势在于您可以随时扩展它们。 -
请您进一步解释一下您的整个代码应该做什么......我仍在试图弄清楚这里应该发生的一切
-
我打算创建一个人工智能。但首先我需要创建一个脚本,它只运行一个向量数组并将刚体设置为这些向量