Static Array

hey people,

i’m trying to create an array with transforms which i can edit or read through another script.
to do this i got to make it a static. but when i type static infront of the variable, it disapeares in the inspector, which is normal.
but now i want to shove some transforms into this array via the inspector, but i cant cause its a static!

how do i fix this?

script i’m using:

	public Transform[] MeleeWeaponCase;

bunch of thanks.

2 Answers

2

Rather than make the array static you should make a singleton - so you have one of these in the scene but a way of finding it quickly:

   public static YourScript instance;

   public Transform[] MeleeWeaponCase;

   void Awake()
   {
        instance = this;
   }

The from elsewhere

  var weapon =  YourScipt.instance.MeleeWeaponCase[0];

i've done some reseach on the singleton, and this is accualy a very good salution to my problem. so i spoke with one of my teachers about it, and it apears this makes all of the info in the script static, and when you use this a lot, then lots of lagg will appear. so he recommended the other awnser. still bunch of thanx for your awnser and fast reply!

I'm afraid I don't agree with your teacher. You only have one piece of information in the script which is the array you are using. Copying it to a static creates spaghetti code and is unnecessary. Nothing in my answer would ever cause your game to lag.

hmm. that sounds true. maybe i'll use it after all. sory if i offended you.

Nope you didn't offend me :) And I'm very sorry if I sounded offended! Just trying to offer my best advice - I know, because it has happened to me - that statics need to be limited and that a singleton pattern fits with your requirements.

Either you didn't explain the situation to your teacher well, or your teacher is an idiot. Personally I don't feel that static references create spaghetti code even if you need to test other configurations, but I can't argue with the wisdom in using a Singleton either. So do it! Singletons have an advantage over pure static classes in that when the instance is initialized you can set up default values that you might not be able to directly because they rely on computed values.

You could create another array that isn’t static, put the transforms in that array and then run:

for(int i = 0; i < NonStaticMeleeWeaponCase.Length; i++){
    MeleeWeaponCase _= NonStaticMeleeWeaponCase*;*_

}
P.S I’m not a master as C# (I just started learning yesterday), so sorry in advance if there are any errors in that.

It's an idea and would work (if you'd resized the array first) - but you are much better off with a singleton.

this worked for me, but i had to use MeleeWeaponCase = NonStaticMeleeWeaponCase; because the for didn't work, and this is faster.