Global Variable Error.

Hello everyone!

I’m working on a fps, and I have a sniper rifle that can zoom up on enemies. But It’s to sensitive to try to snipe enemies from a distance. So, I made a .js script that looks like this:

function Update () {
  if (Input.GetKeyDown("3")) {
	  MouseLook.sensitivityX = 7;
	  MouseLook.sensitivityY = 1;
}
}

Then on my MouseLook script (which is in C# [I didn’t write it]) changed the variables from this:

public class MouseLook : MonoBehaviour {

	public float sensitivityX = 15F;
	public float sensitivityY = 15F;

To this:

public class MouseLook : MonoBehaviour {

	public static float sensitivityX = 15F;
	public static float sensitivityY = 15F;

(There’s more to the script…)

But it gave me 2 errors.

and

How can I fix this? Thanks!

Why did you make them static and how are you accessing them?

I thought when you make them static it makes them a global variable so you can reference them and change them from other scripts.

And I’m accessing them by this piece of code:

MouseLook.sensitivityX = 7;

(MouseLook is my script and sensitivityX is my variable.)

Thanks for helping!

Static doesn’t mean global, it means static. A public variable is global. http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

–Eric

Oops! Thanks for the help.

I can’t get the GetComponent script to work.

The example script is:

// Find the child named "Hand".
// On the OtherScript attached to it, set foo to 2.
transform.Find("Hand").GetComponent(OtherScript).foo = 2;

Then I changed it to fit my scene.

function Update () {
	if (Input.GetKeyDown("3")) {
		transform.Find("FirstPerson Player").GetComponent(MouseLook).sensitivityX = 1;
	}
}

But it gives me a null reference exception error:

Thank you so much for you’re help!!!

Transform.Find is for finding children; you want GameObject.Find.

–Eric

Thanks, I know changed my code to this:

GameObject.Find("FirstPerson Player").GetComponent(MouseLook).sensitivityX = 1;

But it now gives me this error:

Thank you so much Eric for helping me!

A null reference error means the object you’re trying to refer to doesn’t exist. If you have problems figuring out what’s causing the issue, try breaking it into parts instead of doing everything on one line.

–Eric