- Home /
Getting variables after Resources.LoadAll
I have become completely confused by how to load variables in one script from another. Please go easy on me since I'm only just starting with Unity. I'm building a game which will include a large number of ships, so I want to have a separate script to hold various specs for every ship (speed, turning, etc). I'm loading these up via Resources.LoadAll and then trying to access the variables within them from another script, but I'm getting a 'MissingFieldException: Field 'UnityEditor.MonoScript.shipturn' not found.' error.
Here's the script (instantiator) which loads up the ships into an array:
static var ships : Object[];
static var weps : Object[];
function Awake () {
ships = Resources.LoadAll("Ships");
weps = Resources.LoadAll("Weapons");
}
This seems to work normally, I can use print(ships[0]); to return the text of the ship's script file. However, when it comes to accessing one of those variables (shipturn), using the following code, it fails:
playersship=instantiator.ships[playership.playershiptype]; // same as instantiator.ships[0]
var rotationspeed=playersship.shipturn; // errors here
I have a feeling these ship scripts are miscast, but I don't know how to cast them properly. The ship script files contain stuff like the following:
var shipname="testship";
var shipspeed=600;
var shipturn=120;
Thanks in advance for any help.
Answer by Lucas Meijer 1 · May 29, 2010 at 11:02 AM
Resources.LoadALl() is useful when you really need it, but in most cases best avoided. The "usual" way of achieving what you want is:
- import a 3d model for your ship.
- Create a script that gives it some logic, and that has some variables (speed, turnspeed, etc)
- drag the model into your scene
- apply the script
- create a new prefab
- assign the model+script in your scene to the prefab
now you can instantiate that prefab all over the place, and change speeds and turnspeeds.
Good luck, Lucas
Thanks for your response. I looked at doing things that way but I think I may well really need it in the future. It would be much easier to populate the scene with just a couple of lines of code than having to instantiate everything separately or manually put all the prefabs in an array.
I used to feel the same way, but got converted :). Please note that if you prefer code over UI actions, you can also easily write an editorscript that sets things up for you.
Thanks, I'm looking into the editor scripts now and they definitely seem handy.
I managed to solve this now I think, just made a generic shipspec script and dragged it onto each ship I create and then populate its variables through the UI when adding each new ship (hoping to use editor scripts for this). Using GetComponent("shipspec").variable seems to have achieved what I was after, so I'll mark this as solved :)