英文:
How to attach a Spawned GameObject.transform to CinemachineVirualCamera.Follow through script
问题
我正在尝试生成Player并将Player.transform附加到CinamachineVirtualCamera.Follow,以使摄像机跟随玩家。以下是我的脚本。
```c#
使用Cinemachine;
使用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
}
}
}
<details>
<summary>英文:</summary>
[![enter image description here][1]][1]
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.
```c#
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
}
}
}
答案1
得分: 1
你可以使用[SerializeField]
来将变量暴露给检视器,然后可以使用GameObject.Find(gameObjectName).GetComponent<ClassOfObject>();
来查找它们。
你需要添加对相机的引用并使用ResolveFollow
来将玩家的变换传递给它。
[SerializeField] private CinemachineVirtualCameraBase camFollowPlayer;
public void SpawnPlayer()
{
if (playerSpawnPoint != null)
{
GameObject player = playerSpawnPoint.SpawnObject();
camFollowPlayer.ResolveFollow(player.transform);
}
}
英文:
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 CinemachineVirtualCameraBase camFollowPlayer;
public void SpawnPlayer()
{
if (playerSpawnPoint != null)
{
GameObject player = playerSpawnPoint.SpawnObject();
camFollowPlayer.ResolveFollow(player.transform);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论