我正在尝试做一些简单的2D光线投射,我完全迷失了。我在以下脚本的第25行获得了一个空引用异常。我确保敌人被标记为敌人,然而当我尝试获取标签时,我得到了错误。我现在意识到错误只发生在我点击天空时,而不是在没有标记的游戏对象上。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shoot : MonoBehaviour {
public Camera cam;
public GameObject enemy;
public Transform fireStart;
GameObject target;
// Use this for initialization
void Start () {
float inputX = Input.GetAxisRaw("Mouse X");
float inputY = Input.GetAxisRaw("Mouse Y");
fireStart = transform.FindChild("GunEnd");
}
void ShootGun()
{
Debug.Log("Fire");
Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPos = new Vector2(fireStart.position.x, fireStart.position.y);
RaycastHit2D hit = Physics2D.Raycast(firePointPos, mousePos - firePointPos, 100f);
if (hit.collider.CompareTag("Enemy"))
{
Debug.Log("Hit");
}
else if (hit.collider.CompareTag("Untagged"))
{
Debug.Log("No hit");
}
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1"))
{
ShootGun();
}
}
}
非常感谢