我有一个 C# 脚本附加到一个名为 GameManager 的空对象。剧本是GameManager.cs
。这是前几行:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public GameObject tilePrefab;
public GameObject startTile;
public GameObject lastTile;
我在相机上附加了另一个脚本,称为 CameraManager.cs
。我试图从 lastTile
引用 GameManager
但它始终为空。这是 CameraManager.cs
:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraManager : MonoBehaviour
{
// Start is called before the first frame update
private Vector3 currPos;
private Vector3 newPos;
public float CamMoveSpeed = 5f;
GameManager gameManager;
private void Awake() {
gameManager = gameObject.AddComponent<GameManager>();
}
private void Start() {
}
private void Update() {
if (gameManager.lastTile != null) {
currPos = gameObject.transform.position;
Vector3 tilePos = gameManager.lastTile.transform.position;
newPos = new Vector3(currPos.x + tilePos.x, currPos.y + tilePos.y, currPos.z + tilePos.z);
this.transform.position = Vector3.Lerp(currPos, newPos, CamMoveSpeed * Time.deltaTime);
Debug.Log("Moving Camera...");
} else {
Debug.LogWarning("gameManager.lastTile is NULL");
}
}
}
This latest iteration is based on this SO question.之前的迭代是基于this SO question.
从另一个脚本/类引用值的正确方法是什么?
public class GameManager : MonoBehaviour {
public GameObject tilePrefab;
public GameObject startTile;
public GameObject lastTile;
}
看起来您从未将这些变量分配给任何东西,因此它们将始终为空。
为了使它们不为空,您需要将它们分配给某些东西,例如
public class GameManager : MonoBehaviour {
public GameObject tilePrefab = new GameObject("Name");
public GameObject startTile = new GameObject("Name");
public GameObject lastTile = new GameObject("Name");
}
或者你可以通过做动态设置它们
private void Update() {
gameManager.lastTile = new GameObject("Name");
}