unity3d 如何附加一个衍生的游戏对象.transform到CinemachineVirualCamera.遵循脚本[duplicate]

j2cgzkjk  于 2023-02-09  发布在  Mac
关注(0)|答案(1)|浏览(181)
    • 此问题在此处已有答案**:

What is a NullReferenceException, and how do I fix it?(27个答案)
2天前关闭。

我正在尝试生成播放器并附加播放器。转换到CinamachineVirtualCamera。跟随使摄像机跟随播放器。这是我的脚本。

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
        }
    }
}
zlwx9yxi

zlwx9yxi1#

您可以使用[SerializeField]向inspector公开变量,因此您需要使用GameObject.Find(gameObjectName).GetComponent<ClassOfObject>();查找它们
您需要添加对相机的引用,并使用ResolveFollow将播放器变换传递给它。

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

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

相关问题