Helo. I try to get multidimensional array from scriptA in scriptB using inheritance and it seems like after calling this array on scriptB, array is empty.
public class ScriptA : MonoBehaviour
{
protected GameObject[,] boardFields = new GameObject[8, 8];
void Awake()
{
boardFields[4, 0] = GameObject.Find("Canvas/Board/Fields/A4");
Debug.Log(boardFields[4, 0]); //here i see in the console that the variable is not empty
//rest of the code
}
}
public class ScriptB : ScriptA
{
void Start()
{
Debug.Log(boardFields[4, 0]); //and here i get null in the console
}
}
I also checked another variables and it seems that the problem is only with arrays. How can i use this array in scriptB? Sorry for maybe stupid question but i just started with object programming
You’re violating two different Unity “customs” here.
You’re using inheritance. By default Unity users and the way scripts are defaulted are NOT set up for this. Yes it works, but using it will open yourself to constant future headaches when you (or others) misuse your code, not noticing that it is derivative of something else derivative of a MonoBehaviour (for example)
you’re using GameObject.Find(). That almost always ends in disasters.
In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY. If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.
For instance, just make a board controller with public fields for what you need and fill it out on each instance of your board.
When I change Awake() modifier to protected i got a lot of warnings (from another script) and still doesn’t working but i make another protected function and it’s work. Thanks a lot!
There is many ways a variable can be filled through. If its a fixed relation which already exists in the scene, yes, the inspector would be a good place. For example, you could assign the 4 wheels of a car to the body through the inspector. But this cannot be applied to every situation. In other cases, for example, the relation may be set up through a collision, or through equipping an item from an inventory dynamically. But generally speaking, there is never a good reason to use Find(). This is true for 99.9% of all Unity developers. There is certain usecases where you cannot avoid it, but for all practical intents and purposes of creating a game, there is always a more appropriate solution.