- Home /
Question about creating variables to hold scripts.
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!
Answer by cjdev · Sep 28, 2015 at 07:14 AM
The reason it's not working is because your script isn't of type MonoBehaviour, it inherits from it. The difference is that the functions from the MonoBehaviour class are available to the inheriting class, but if you were to treat the class as a MonoBehaviour object then it wouldn't know about any of the functions you defined in your base class because they aren't also defined in Monobehaviour.
In order to call the function from your script you need to store it in a variable of it's own type, PlayerSpawnController. Then you'll have access to all of the functions and variables you've defined in that type.
Your answer
Follow this Question
Related Questions
Why does monobehavior in if statement compiles? 1 Answer
Access variables,method from a Mono Behaviour without static use. -1 Answers
Monobehaviour resets variables after the initialization cycle 0 Answers
Public variable containing script 2 Answers
Trying to get access to variables in the editor script 4 Answers