首页 > 解决方案 > 找不到类型或命名空间名称 Unity

问题描述

我正在为我的 fps 游戏编写脚本,但我仍然收到此错误“找不到类型或命名空间名称‘目标’。” 我知道这行代码有问题,ReactiveTarget target = hitObject.GetComponent<Target>();但我不知道它找不到这个 Target 类

using UnityEngine;
using System.Collections

public class Shooting : MonoBehaviour{
private Camera _camera;

void Start(){
    _camera = GetComponent<Camera>();
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

void OnGUI()
{
    int size = 12;
    float posX = _camera.pixelWidth / 2 - size / 4;
    float posY = _camera.pixelHeight / 2 - size / 2;
    GUI.Label(new Rect(posX, posY, size, size), "*");
}

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {

        Vector3 point = new Vector3(_camera.pixelWidth / 2, _camera.pixelHeight / 2, 0);

        Ray ray = _camera.ScreenPointToRay(point);

        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            GameObject hitObject = hit.transform.gameObject;

            ReactiveTarget target = hitObject.GetComponent<Target>();

            if (target != null)
            {
                target.ReactToHit();
            }
         
            else
            {
                StartCoroutine(SphereIndicator(hit.point));
            }
        }
    }
}
private IEnumerator SphereIndicator(Vector3 pos)
{
    GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
    sphere.transform.position = pos;
    yield return new WaitForSeconds(1);
    Destroy(sphere);
}}

这是目标脚本

using UnityEngine;
using System.Collections;


public class Target : MonoBehaviour
{
    public void ReactToHit()
    {
        StartCoroutine(Die());
    }
    private IEnumerator Die()
    {
        this.transform.Rotate(-75, 0, 0);
        yield return new WaitForSeconds(1.5f);
        Destroy(this.gameObject);
    }
}

标签: c#unity3d

解决方案


你好

这里有问题(或者至少这是我的想法)

你是如何使用数据类型ReactiveTarget来获取Target的数据类型的?

这是我第一次看到这样的东西!

尝试改变

ReactiveTarget target = hitObject.GetComponent<Target>();

到:

Target target = hitObject.GetComponent<Target>();

推荐阅读