首页 > 解决方案 > 为什么更新不起作用(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);

        }
        
    }
}

标签: c#unity3d

解决方案


当您没有将值分配给变量时,会出现这种类型的错误。在这种情况下,我认为 playerTransform 为空。您可以在检查器中查看公共(或序列化)变量,单击您将此脚本分配给的游戏对象。


推荐阅读