x


Difficulty Accessing Static Variable

I have declared a static string in one script component of a gameobject, and am trying to access it in a script component of another game object. The static string is declared here:

public class PlayerStatus : MonoBehaviour 
{
    public static string mainStatus = "1";
}

In the other script, I attempt to print the string to console and eventually use the string in some methods.

public class Player : MonoBehaviour 
{
    GameObject statusContainer;
    string currentStatus;

 void Start() 
    {
       statusContainer = GameObject.Find("StatusContainer");
       currentStatus = statusContainer.GetComponent<PlayerStatus>().mainStatus;
       print(currentStatus);
    }
}

The script as such gives the error:

"Static member `PlayerStatus.mainStatus' cannot be accessed with an instance reference, qualify it with a type name instead"

I've tried putting the script containing the static string into the Standard Assets folder to make sure it gets compiled first, so that's not a problem.

more ▼

asked Jul 18 '12 at 05:41 PM

Ishkur gravatar image

Ishkur
69 5 9 11

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

A static string does not exist on a class instance. In this case you have a PlayerStatus class instance on statusContainer.

To access mainStatus.. you would do something like this..

currentStatus = PlayerStatus.mainStatus;

But that won't work for your case, as it seems you want the value of mainStatus on a specific PlayerStatus gameObject instance.

So simply change your declaration to

public string mainStatus = "1";

I'd also suggest reading up on code formatting best practices. Public variables are usually in Capitals.

So

public string MainStatus = "1";
more ▼

answered Jul 18 '12 at 06:49 PM

Meltdown gravatar image

Meltdown
5.6k 18 25 49

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x847
x284
x49

asked: Jul 18 '12 at 05:41 PM

Seen: 539 times

Last Updated: Jul 18 '12 at 08:01 PM