Get gameObjects from a protected GameObject array of base class in derived class
I have a StageScript
in which I am filling an array in the inspector named UnorthodoxSeats
marking it as [SerializeField] protected GameObject[] UnorthodoxSeats
in the script. When the script runs, after some time a Character is instantiated to move towards the seat. The Character has also a script named CharacterScript
which is the derived class of StageScript
. Now, In the CharacterScript
whenever I get UnorthodoxSeats.Length
it shows 0
. I am confused why?
Any help would be awesome.
Can you edit your question and provide more code (class A and B), a screenshot of the inspector with your gameObject holding the component B
and the full message in the console?
Sorry but the way you describe your class definitions and the declaration of your array is not enough to figure out what you might have done wrong. Why don't you post the relevant code? Are you sure that you do not overwrite the array somewhere in Start or Awake?
`public class StageScript
{
[SerializeField] protected GameObject[] UnorthodoxSeats;
// not using awake
// start only have invokeRepeating method but that method is not related to UnorthodoxSeats
}
public class CharacterScript : StageScript
{
private Start()
{
Debug.Log(UnorthodoxSeats.Length);
}
}`
If the base class has a Start method also (even one that doesn't touch the array), you will need to specify the override keyword for the Start method in the derived class, AND invoke the base class's version manually e.g. base.Start();
, from inside it.
As a sanity check- I suggest you display the array length in both base and derived class versions of Start: I expect they will display the same results; if so, this a clue that one of your assumptions is incorrect.
Answer by Kennai · Jun 21, 2019 at 06:57 AM
Hi, @OsamaSany! I suppose that you work with two different instances.
One instance is type of StageScript, where you filled field.
And another instance is type of CharacterScript, which has empty field, because it is other instance.
If you need to share field between classes - use static field!
Yes I think it was that. I made the array public and created a place holder for Stage in the character script and accessed it as the characters great grand parent and accessed the stage script and array from that place holder and it is working fine now.
Your answer
![](https://koobas.hobune.stream/wayback/20220612203535im_/https://answers.unity.com/themes/thub/images/avi.jpg)