I have a C# script attached to an empty object called GameManager. The script is GameManager.cs
. Here are the first few lines:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public GameObject tilePrefab;
public GameObject startTile;
public GameObject lastTile;
I have another script attached to a camera called CameraManager.cs
. I'm attempting to reference lastTile
from GameManager
but it's always null. Here is the full code for 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. The previous iteration was based on this SO question.
What is the proper way to reference a value from another script/class?