This should be a quick one.
I have an enemy class which stores a reference to the room (with a room being a separate monobehaviour script) its located in. I wanted this to be a private variable with a Get()
and Set()
function so that it doesn’t come up in the inspector. For some reason, the reference becomes null if I set it when it’s private.
Here is the code where I set the room before I spawn the enemy:
foreach (GameObject e in roomEnemies)
{
e.GetComponent<Enemy>().SetRoom(this);
Instantiate(e, transform.position + Vector3.one * Random.Range(-8f, 8f), Quaternion.identity);
}
and here is the code where I later retrieve the room from the enemy in a different component script on the same object:
private void Start()
{
pathFinding = GetComponent<Enemy>().GetRoom().GetPathfinding();
}
Interestingly, if I set the room reference to be public, it works fine and returns the room without any issues.
I know that I could just set the variable to be public and hide it in the inspector, but I feel like that’s sloppy programming and, more than anything, I just want to understand why this is happening.
Thank you programming wizards!