- Home /
Prefab not loading in data from Inspector
Okay. What I'm trying to do is create an array of prefabs, but I'm having trouble properly creating them and placing them in the array. I've tried several things so far, but these two actually compile and don't crash immediately:
// 1. An array of GameObjects
public GameObject[] Weapons;
// Setting array size
Weapons = new GameObject[(int)WeaponBase.WeaponType.NumTypes];
Weapons[0] = GameObject.Find("MachineGun");
// 2. An array of base-class scripts
public WeaponBase[] Weapons;
// Setting array size
Weapons = new WeaponBase[(int)WeaponBase.WeaponType.NumTypes];
Weapons[0] = gameObject.AddComponent<WeaponBase>();
Neither of these options assigns the values from the prefab's Inspector upon creation, but the objects do get created, and are assigned the values within their ctor. I used to be able to Instantiate this prefab before I implemented the array, but since that's not working, nothing else is.
Any help would be appreciated. Thanks!
Answer by barbe63 · Jul 10, 2015 at 03:36 AM
Your Weapons array is immedialty overriden on the run by this line:
Weapons = new GameObject[(int)WeaponBase.WeaponType.NumTypes];
Which is creating a new array... What you need to do is:
public GameObject[] Weapons = new GameObject[(int)WeaponBase.WeaponType.NumTypes];
// in the declaration you can set the size without override what is in inspector
As I'm not sure it would compile because of the (int)WeaponBase.WeaponType.NumTypes not being accesible in the declaration (I honestly don't know) the 2 alternatives you have are:
Set the size in script like this: public GameObject[] Weapons = new GameObject[12];
Set the size manually in inspector
What I ended up doing was your first bullet, the public GameObject[] Weapons = new GameObject[num];
Then I created factory methods that instantiated new weapons and placed them in their respective array slots.
What I think the problem was (sorry it took me so long to reply) was that I had ctors in the derived class attached to the prefabs, and they were being called, thus overriding what was in the inspector, even though they were empty. I took those out and just made an Init() that was called after creation. Everything works now that there's a factory. Thanks for your quick input!
Your answer
Follow this Question
Related Questions
Staged Prefab can't "Apply" after adding using Gameobject as a variable 1 Answer
Array of Arrays of GameObjects/Prefabs (C#) 1 Answer
Get Script from gameobject knowing only parent script 1 Answer
Can a GameObject inside of an array be made "accessible" from the editor? 2 Answers
Creating an array of prefabs? 4 Answers