-2

in my unity game I'm creating a Menu and and I want to move the camera with the player, when the game is started and I want to move the camera in the right position before (Vector3(1, 1, -1)). The problem is that I am using a Button connected with a script setting a public bool variable. But whatever I do, the NullReferenceException Error appears.

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);

        }
        
    }
}
Ruzihm
  • 16,769
  • 3
  • 27
  • 40
  • Well the value of the variable is `null` and therefore it will cause a `NullReferenceException`. What variable is `null` and on which line? – JohannesAndersson Nov 27 '20 at 20:19

1 Answers1

0

This type of error appear when you didn't assign the value to a variable. In this case, i suppose that playerTransform is null. You can check this watching the public (or serialized) variables in the inspector clicking the gameObject you assigned this script to.

Alman1236
  • 1
  • 1