Hey everybody, so I have a script that is giving me an error… I already know how to fix it, but I was just wondering if someone could explain why it doesn’t work to begin with in the first place. Like why can’t I create a variable of type MonoBehavior, assign it a value using GetComponet to get a script from an object, and then from that point on refer the that variable by name and start accessing the methods etc. from the other script??
The script looks like this: Note, the component PlayerSpawnController is another script attached to a game object.
public class GameState : MonoBehaviour
{
private GameObject player;
private MonoBehaviour playerSpawnCTRL;
private GameObject randPlayerSpawn;
void Awake()
{
player = GameObject.FindWithTag("Player");
playerSpawnCTRL = GameObject.FindGameObjectWithTag("PlayerSpawnCTRL").GetComponent<PlayerSpawnController>();
}
// Use this for initialization
void Start ()
{
randPlayerSpawn = playerSpawnCTRL.GetRandomPlayerSpawn(); // <-- this is the line with the error.
Debug.Log (randPlayerSpawn);
SpawnPlayer();
}
/*The compiler states that randPlayerSpawn does not contain a definition for “GetRandomPlayerSpawn” as randPlayerSpawn is of type MonoBehavior. But if I’ve assigned randPlayerSpawn a script using GetComponet, why can’t I now refer to that script’s public variables and methods etc. Like why does the above line not work given this scenario, but the following line below works. */
void Start ()
{
randPlayerSpawn = GameObject.FindGameObjectWithTag("PlayerSpawnCTRL").GetComponent<PlayerSpawnController>().GetRandomPlayerSpawn();
Debug.Log (randPlayerSpawn);
SpawnPlayer();
}
}
Thanks for your help!