Camera.main空引用异常 [英] Camera.main null reference exception
问题描述
我是C#和Unity的新手,并且我已经阅读了整个论坛,但仍然很困惑.这是我得到的错误:
I am new to C# and Unity and I have read this entire forum and I am still stuck. This is the error I am getting:
NullReferenceException:对象引用未设置为对象的实例 ClickToMove.Update()(位于Assets/Scripts/ClickToMove.cs:27)
NullReferenceException: Object reference not set to an instance of an object ClickToMove.Update () (at Assets/Scripts/ClickToMove.cs:27)
这就是我所拥有的...
This is what I have...
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 ..."开头
Line 27 starts with "Ray ray = Camera.main.ScreenPointToRay..."
推荐答案
您需要在场景中使用带有MainCamera
标签的摄像机才能调用Camera.main.ScreenPointToRay()
.没有这个,Camera.main
将不存在,从而导致空引用异常.
You need to have a camera in your scene with the MainCamera
tag in order to call Camera.main.ScreenPointToRay()
. Without this, Camera.main
does not exist, resulting in a null reference exception.
这篇关于Camera.main空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!