c# - 我正在尝试制作一个损坏脚本,但它出现了一个错误,说名称空间“播放器”无法识别
问题描述
这是我的代码:
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 很陌生
解决方案
您的项目中应该有(或创建)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);
}
}
}
}
}
干杯!
推荐阅读
- javascript - 将两个 var 合并为一个 if 语句时遇到问题
- linux - 删除列 csv 文件,其中一些包含带引号的文本,包括逗号
- django - 将原始 SQL 转换为 Django ORM QuerySet
- azure - 关于 Azure (Terraform) 中虚拟机“计划”的问题
- angular - 纱线:“不正确的对等依赖”我:?
- java - 将 postgres 枚举映射到 java 字符串
- gitlab - GitLab 每个分支一页
- javascript - 关于循环变量的 JavaScript 问题
- r - 将 http 1.1 设置为默认 libcurl linux
- python - pandas:将 DataFrame 拆分为 Series 会导致 NaN