我最近一直在关注 youtube 上“Brackeys”的塔防游戏教程,我逐字逐句地照做了,但有一个错误(在下面的照片中)不会让我的敌人预制件移动在现场。预制件都在产卵,但卡在一个地方。 任何帮助将不胜感激
谢谢,米奇
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float speed = 10f;
private Transform target;
private int wavePointIndex = 0;
// Use this for initialization
void Start()
{
// An error pops up on the first frame for this line of code below
target = Waypoints.points[0];
}
// Update is called once per frame
void Update ()
{
// This is the main source of the error below.
Vector3 dir = target.position - transform.position;
transform.Translate (dir.normalized * speed * Time.deltaTime, Space.World);
if (Vector3.Distance (transform.position, target.position) <= 0.4f)
{
GetNextWayPoint ();
}
}
void GetNextWayPoint()
{
if (wavePointIndex >= Waypoints.points.Length - 1)
{
Destroy (gameObject);
return;
}
wavePointIndex++;
target = Waypoints.points[wavePointIndex];
}
}
error description in unity Enemy prefab that has script on it
最佳答案
您上传的图片显示您命名为 Enemy
脚本 EnemyMover
在你的编辑器中。这不是问题,但您应该始终发布场景中的脚本名称以避免混淆。
根据您的说法,这行代码是问题所在:target = Waypoints.points[0];
问题是points
是 Transform
的数组并且未初始化。
存在三种可能的问题:
1。您的 Waypoint
脚本未附加到 Waypoints 游戏对象。
选择Waypoints GameObject,拖动Waypoint
脚本。它必须附加到您的 Waypoints GameObject 才能初始化
points
数组变量。
2。您的 Waypoint
脚本附加到多个游戏对象。确保 Waypoint
脚本仅附加到一个游戏对象,并且该游戏对象是所有路径点的父级。这个游戏对象被命名为Waypoints。
要验证这一点,请选择 Waypoint
项目选项卡中的脚本,右键单击它并单击在场景中查找引用。它会向您显示每个 GameObject Waypoint
附上脚本。如果它附加到任何未命名为 Waypoints 的游戏对象,请从该游戏对象中删除脚本。
3.Waypoint
中的函数脚本在你的 Enemy
之前被调用脚本。在 Unity 中有时会发生这种情况。
转到编辑->项目设置->脚本执行顺序。拖动 Waypoint
将脚本放入订单中然后拖动 Enemy
顺序中的脚本。点击应用。
问题 #3 的第二种解决方案是删除 static
关键字并使用 GameObject.Find("Waypoints");
和 GetComponent<Waypoint>();
.您可以找到完整的脚本,这两个脚本都是 here和 here .请注意,如果您按照第二种解决方案删除 static
关键字,您可能很难理解本教程的其余部分。
关于c# - 敌人脚本在我的塔防游戏 c# 上无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39033359/