c# - 敌人脚本在我的塔防游戏 c# 上无法正常工作

标签 c# unity3d

我最近一直在关注 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];

问题是pointsTransform 的数组并且未初始化。

存在三种可能的问题:

1。您的 Waypoint脚本未附加到 Waypoints 游戏对象。 选择Waypoints GameObject,拖动Waypoint脚本。它必须附加到您的 Waypoints GameObject 才能初始化 points数组变量。

2。您的 Waypoint脚本附加到多个游戏对象。确保 Waypoint脚本仅附加到一个游戏对象,并且该游戏对象是所有路径点的父级。这个游戏对象被命名为Waypoints

要验证这一点,请选择 Waypoint项目选项卡中的脚本,右键单击它并单击在场景中查找引用。它会向您显示每个 GameObject Waypoint附上脚本。如果它附加到任何未命名为 Waypoints 的游戏对象,请从该游戏对象中删除脚本。

3.Waypoint 中的函数脚本在你的 Enemy 之前被调用脚本。在 Unity 中有时会发生这种情况。

转到编辑->项目设置->脚本执行顺序。拖动 Waypoint将脚本放入订单中然后拖动 Enemy顺序中的脚本。点击应用。

enter image description here

问题 #3 的第二种解决方案是删除 static关键字并使用 GameObject.Find("Waypoints");GetComponent<Waypoint>(); .您可以找到完整的脚本,这两个脚本都是 herehere .请注意,如果您按照第二种解决方案删除 static关键字,您可能很难理解本教程的其余部分。

关于c# - 敌人脚本在我的塔防游戏 c# 上无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39033359/

相关文章:

c# - MVC 如何防止通过名称调用 Action Method 而只允许通过路由调用它

Android 工作室项目到 Unity 5

unity3d - Linux 上的 UnityHub "Not Enough Space"错误

c# - 偏移量的光线转换

c# - 如何在不使用 EF 的情况下连接到 ASP.NET Core Web API 中的数据库?

c# - System.Diagnostics.Process.Start 奇怪的行为

c# - 无法加载文件或程序集 'System.Private.CoreLib...'

c# - XAML数据绑定(bind),对象与目标类型不匹配

ios - 我如何只响应 UI 图像中的触摸?

c# - 相对于它始终面对的点移动对象会导致螺旋轨道