【问题标题】:Enemy Script Isn't working properly on my Tower Defense game c#敌人脚本在我的塔防游戏 c# 上无法正常工作
【发布时间】:2016-08-19 17:21:30
【问题描述】:

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

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您上传的图片显示您在编辑器中将Enemy 脚本命名为EnemyMover。这不是问题,但您应该始终发布场景中的脚本名称以避免混淆。

    按照你的说法,这行代码就是问题所在:target = Waypoints.points[0];

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

    存在三个可能的问题:

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

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

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

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

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

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

    【讨论】:

    • 第一个解决方案解决了我的问题!最困扰你的总是简单的问题
    • 不错。它可能是其中之一。不要忘记接受答案。
    • 我投了票,但它说我没有足够的积分今天才开始使用这个谢谢一堆
    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多