- Home /
Global array list c#
Hello, I'm sorry I don't quite know how to do code snippets here. I have two scripts, a general sort of one which manages an array list and then a second which I wish to access the array list from.
So in the manager script (called PlayerManager) I have:
public ArrayList playerList = new ArrayList();
public class PlayerEntry
{
public string name;
public NetworkPlayer player;
}
Then in my other script I wish to access this array list and add new entries. The following commands attempt to create a new entry to this array list.
PlayerManager.PlayerEntry newEntry = new PlayerManager.PlayerEntry();
newEntry.name = playerName;
newEntry.player = Network.player;
PlayerManager.playerList.Add(newEntry);
The first command works where the program is able to create the temporary entry. However, the error appears to be on the final line where I actually attempt to access the list itself.
The error code itself is:
error CS0120: An object reference is required to access non-static member `PlayerManager.playerList'
The unity script reference implies that this is how you access global variables from another function with script.variable. Does anyone know what I am doing wrong?
The class is not static. I make the array list static and it seems to work now. Adding static to the class so that it is:
public static class Player$$anonymous$$anager : $$anonymous$$onoBehaviour {
gives the following error:
error CS0713: Static class Player$$anonymous$$anager' cannot derive from type
UnityEngine.$$anonymous$$onoBehaviour'. Static classes must derive from object
I'm not really sure how to make a class static in c#.
Thanks for your help guys. I would up vote your answer fishspeaker but I don't seem to have that ability.
Yeah, if you want Player$$anonymous$$anager to be a $$anonymous$$onoBehaviour, it can't be static. $$anonymous$$onoBehaviours end up being Components on GameObjects, and the whole architecture depends on them being instantiated.
You don't need a static class to make a static variable, though.
You should have enough $$anonymous$$arma to upvote now.
Answer by FishSpeaker · Jun 06, 2012 at 09:09 PM
You need to declare playerList as static to access it as you describe:
public static ArrayList playerList = new ArrayList();
But it may make more sense to keep playerList as an instance variable, and instead access it from a PlayerManager instance. Assuming PlayerManager is a MonoBehaviour on some GameObject, it would look something like:
gameObject.GetComponent<PlayerManager>().playerList.Add(newEntry);
It all depends on how you have things setup.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Problem with Accessing Variables from Other Scripts in c#. 1 Answer
create a dynamic menu 1 Answer
SOLVED Accessing an other C# script and run a function 1 Answer