c# - 为什么更新不起作用(NullReferenceException)
问题描述
在我的统一游戏中,我正在创建一个菜单,并且我想与玩家一起移动相机,当游戏开始时,我想将相机移动到之前的正确位置 (Vector3(1, 1, -1)) . 问题是我正在使用与设置公共布尔变量的脚本连接的按钮。但无论我做什么,都会出现 NullReferenceException 错误。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartPosition : MonoBehaviour
{
public bool cameraFollow;
public void TakeStartPosition()
{
transform.position = new Vector3(1, 1, -1);
cameraFollow = true;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform playerTransform;
public StartPosition followOn;
private Vector3 cameraOffset;
[Range(0.01f, 1.0f)]
public float smoothFactor = 0.5f;
// Start is called before the first frame update
void Start()
{
if (followOn.cameraFollow)
{
cameraOffset = transform.position - playerTransform.position;
Debug.Log("It must work!!!");
}
}
// Update is called once per frame
private void LateUpdate()
{
if (followOn.cameraFollow)
{
Vector3 newPos = playerTransform.position + cameraOffset;
newPos.z = transform.position.z;
transform.position = Vector3.Slerp(transform.position, newPos, smoothFactor);
}
}
}
解决方案
当您没有将值分配给变量时,会出现这种类型的错误。在这种情况下,我认为 playerTransform 为空。您可以在检查器中查看公共(或序列化)变量,单击您将此脚本分配给的游戏对象。
推荐阅读
- python - 我想在产品有折扣价时显示折扣价
- python - 使用 QAbstractTableModel 在 pyqts QTableView 中插入和删除行
- python - 使用窗口和层次逻辑使用 Pandas 创建计算列
- azure - Azure ADDS 的域控制器策略
- algorithm - 如何找到具有 k 个负加权边的最短路径?
- c# - 记录 ASP.net 核心 Lambda 应用程序日志
- windows - Using git submodules as junctions in Windows
- apache-spark - Azure Data Lake Gen 2 存储中的 Parquet 与 Delta 格式
- python - 升级到最新的 moto 版本(1.3.15 和 1.3.16)后测试中断
- slurm - 作业未获得请求的内存