You know, gents, I'm not quite sure that the manual/scripting reference entries on this stuff is very helpful... Anyway.
I'm currently trying to streamline the process of damaging enemies in order to remove some issues that pop up. What I'm wanting to do is create a master array script that has a number of arrays for Enemies, Items, and the like. That works just fine; the issue is accessing said arrays in other scripts. Now, the coding for damage is like this:
The part attached to the player that has the damage amount, as well as the part that actually sends the damage (Attack.js):
And the part on the enemy that receives the damage (enemyHealth.js):
(isInRange is determined by whether or not the enemy is within a certain hitbox)
And then the master array (LevelArrays.js):
I need to be able to access the Enemy array from the LevelArrays script in the Attack script, but even with the information provided on using GetComponent and the like, I'm completely in the dark on how to do this. What say you?
asked Jun 26 '11 at 06:38 AM
Making the arrays static in JS will effectively make them function as a singleton. What I usually do is set up one object as a sort of master object with a particular tag that I would call GameObject.FindWithTag during Start or Awake to grab a reference to and store within a private var within the client script.
In this way, you just access them like this
answered Jun 26 '11 at 10:00 AM
I always try to encapsulate the data where it belongs - in objective oriented style. That is, I keep the logic within the object.
I do maintain an array in my "GameLoopController"(GLC) script too. But if its inside the GLC, then the other objects doesnt have access to it.
See it like a tree, the root knows its children and asks them. Then I make "public" functions in the objects that allows me to ask them if they are hit, if they give points etc.
If I need them to return upon an event I utilize eventlistners.
So regarding your question.
I believe you need to make the arrays PUBLIC, in C# you just add the word: public in front of the variables when declaring them.
But I still dont see why your main loop should make this array public accessable to your other objects, unless its a bit messy object hierachy your are building?
answered Jun 26 '11 at 12:29 PM
Make your arrays static.
To access from any script:
(I've been using C# more than UnityScript lately, so if my brain somehow mixed things up, then just post a comment and I'll take out my UnityScript hat for a bit. =P)