首页 > 解决方案 > 我正在尝试制作一个损坏脚本,但它出现了一个错误,说名称空间“播放器”无法识别

问题描述

这是我的代码:

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class Obstacle : MonoBehaviour
{
    public int damage = 1;
    public float speed;
    private void Update() 
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player")) {
            other.GetComponent <Player> ().health -= damage;
            Debug.Log(other.GetComponent<Player>().health);
            Destroy(gameObject);
        }
    } 
}

线条

other.GetComponent <Player> ().health -= damage;
Debug.Log(other.GetComponent<Player>().health);

是什么导致错误。这是出现的错误:Assets\Scripts\Obstacle.cs(17,33): error CS0246: The type or namespace name 'Player' could not be found(您是否缺少 using 指令或程序集引用?)任何非常感谢您的帮助,如果这是一个愚蠢的问题,我深表歉意,我对 c# 和 Unity 很陌生

标签: c#unity3d

解决方案


您的项目中应该有(或创建)Player.cs 脚本(类)。它可以在项目选项卡中用鼠标右键创建:创建/C# 脚本。

为了避免您的异常(错误),它可能看起来像这样:

using UnityEngine;

public class Player : MonoBehaviour
{
    public float health = 5;
}

如果生命值低于或等于 0,您也可能想要杀死(销毁)对象。在这种情况下,您的脚本可能如下所示:

using UnityEngine;

public class Obstacle : MonoBehaviour
{
    public int damage = 1;
    public float speed = 1;

    void Update()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            Player player = other.GetComponent<Player>();

            //If "other" Game Object has Player component.
            if (player)
            { 
                player.health -= damage;
                Debug.Log(player.health);

                if(player.health <= 0)
                {
                    Destroy(gameObject);
                }
            }
        }
    }
}

干杯!


推荐阅读