gpt4 book ai didi

c# - Camera.main 空引用异常

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:55 25 4
gpt4 key购买 nike

我是 C# 和 Unity 的新手,我已经阅读了整个论坛,但我仍然被困住了。这是我收到的错误:

NullReferenceException: Object reference not set to an instance of an object ClickToMove.Update () (at 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...”开头

最佳答案

为了调用 Camera.main.ScreenPointToRay(),您需要在场景中使用带有 MainCamera 标签的相机。没有这个,Camera.main 不存在,导致空引用异常。

enter image description here

关于c# - Camera.main 空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52242441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com