c# - Camera.main 空引用异常
问题描述
我是 C# 和 Unity 的新手,我已经阅读了整个论坛,但我仍然陷入困境。这是我得到的错误:
NullReferenceException:对象引用未设置为对象 ClickToMove.Update () 的实例(在 Assets/Scripts/ClickToMove.cs:27)
这就是我所拥有的...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class ClickToMove : MonoBehaviour {
[Header("Stats")]
public float attackDistance;
public float attackRate;
private float nextAttack;
private NavMeshAgent navMeshAgent;
private Animator anim;
private Transform targetedEnemy;
private bool enemyClicked;
private bool walking;
void Awake ()
{
anim = GetComponent<Animator>();
navMeshAgent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update ()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetButtonDown("Fire2"))
{
if (Physics.Raycast(ray, out hit, 1000))
{
if (hit.collider.tag == "Enemy")
{
targetedEnemy = hit.transform;
enemyClicked = true;
//print("Enemy Hit");
}
else
{
walking = true;
enemyClicked = false;
navMeshAgent.isStopped = false;
navMeshAgent.destination = hit.point;
}
}
}
if (enemyClicked)
{
MoveAndAttack();
}
if (navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance)
{
walking = false;
}
else
{
walking = true;
}
//anim.SetBool("isWalking", walking);
}
void MoveAndAttack()
{
if(targetedEnemy == null)
{
return;
}
navMeshAgent.destination = targetedEnemy.position;
if(navMeshAgent.remainingDistance > attackDistance)
{
navMeshAgent.isStopped = false;
walking = true;
}
else
{
transform.LookAt(targetedEnemy);
Vector3 dirToAttack = targetedEnemy.transform.position - transform.position;
if(Time.time > nextAttack)
{
nextAttack = Time.time + attackRate;
}
navMeshAgent.isStopped = true;
walking = false;
}
}
}
第 27 行以“Ray ray = Camera.main.ScreenPointToRay...”开头
解决方案
推荐阅读
- javascript - 如何连接到 Firebase Firestore?
- flutter - Flutter:区分 Widget param = null 和未设置的参数
- redis - Redis 是否支持具有多个节点的哨兵设置中的数据库?
- reactjs - Office 加载项对话框无法获取 /popup.html
- rest - OTRS 通过 REST API 登录
- mysql - 我只是试图创建一个 sql 查询但没有得到
- mysql - mysql 根据输入按前四或三或两组行排序
- android - Android UE4 错误缺少“SteamShared”的预编译清单
- python - 找不到正确的编码来从 Excel 中解码中文
- python - 通过 Git 共享 conda 环境:最佳实践是什么?