- Home /
Problems accessing other script's variable
Hey guys! I'm making a game in which you have two scripts (for now): One main that is attach to the camera and calculate the MousePosition to use it and another one that needs to access it too.
Here are the scripts:
Script One
public class Spawner : MonoBehaviour
{
public Vector3 worldPosition;
void FixedUpdate()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = 2f;
worldPosition = camera.ScreenToWorldPoint(mousePosition);
}
}
Script Two
public class PreSpawner : MonoBehaviour
{
public Spawner spawner;
void FixedUpdate()
{
float wpX = spawner.worldPosition.x;
}
}
Now, each time I hit Play, it returns this error at each frame:
NullReferenceException: Object reference not set from an instance of an object PreSpawner.FixedUpdate() (at Assets/Scripts/PreSpawner.cs:7)
I read some post on that question, but none of the answers seemed to fit my situation.
Anobody can help with it??
Or you could justSee comment above.
public Spawner = GetComponent(OtherScript);
Answer by ramp · Jan 21, 2015 at 12:35 PM
Hello,
Your code is working fine,need to expose references to other objects to the inspector. Below you can drag a game object(i.e. Main Camera) that contains the Spawner script on the spawner slot in the inspector. Below i attached screenshot like this,may be help.
Thanks! I tried to drag the script itself and it didn't work... So now I know how to! But I make it in runtime using GameObject.Find(). It will be hard to use the Inspector because pretty all my game is generated in runtime ;)
Your answer
Follow this Question
Related Questions
NullReferenceException (C#) 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
Bought an asset that uses C#, I'm a UnityScript guy 2 Answers