0

enter image description here

I'm trying to spawn the Player and attach the Player.transform to CinamachineVirtualCamera.Follow to make the camera follow the player. And here is my script.

using Cinemachine;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager sharedInstance = null;
    private SpawnPoint playerSpawnPoint;
    private CinemachineVirtualCamera camFollowPlayer;
    private void Awake()
    {

        if (sharedInstance != null && sharedInstance != this)
            Destroy(gameObject);
        else sharedInstance = this;
    }
    private void Start()
    {
        playerSpawnPoint = GameObject.Find("PlayerSpawnPoint").GetComponent<SpawnPoint>();
        SetupScene();
    }
    public void SetupScene()
    {
        SpawnPlayer();
    }
    public void SpawnPlayer()
    {
        if (playerSpawnPoint != null)
        {
            GameObject player = playerSpawnPoint.SpawnObject();
            camFollowPlayer.Follow = player.transform;    //my code got error NullExceptionReference here
        }
    }
}
Tien Hung
  • 139
  • 8
  • 1
    You probably forgot to assign a reference in the editor: https://www.google.com/search?b-d&q=unity+object+reference+not+set+to+an+instance+of+an+object – Absinthe Feb 06 '23 at 10:07

1 Answers1

1

You can expose variables to inspector with [SerializeField] so you would need to look for them with GameObject.Find(gameObjectName).GetComponent<ClassOfObject>();

You need to add reference to the Camera and use ResolveFollow to pass player transform to it.

[SerializeField] private Cinemachine​Virtual​Camera​Base camFollowPlayer;

public void SpawnPlayer()
    {
        if (playerSpawnPoint != null)
        {
            GameObject player = playerSpawnPoint.SpawnObject();
            camFollowPlayer.ResolveFollow(player.transform); 
        }
    }