- Home /
GetComponent with arrays C#?
Ok it may seem simple but I need to transfer a 2d array from one c# script (TileGeneration) to the other script (PlayerAI). The TileGeneration script is located on a gameobject called Chunk and the PlayerAI script is located on a gameobject called Player.
//This is the Script with the array Tile[,] (which is a int array)
public int[,] Tile;
void Start()
{
Tile = new int[20, 20];
}
----------
//This is the second script
GameObject Object1 = GameObject.Find("Chunk");
TileGeneration Script1 = Object1.GetComponent<TileGeneration>();
waypoints = Script1.Tile;
Any help will be appreciated, Thank you in advance.
So why is this not working for you? How is waypoints declared?
What's the problem? The scripts seem ok. Have you declared waypoints as int[,] in the second script?
yes I did waypoints was declered as, public int[,] waypoints; but I have solved his by not using getcomponent but by making Tile a public static and that had seemed to solved it. Thank you for the help though.
And you should not do that. You are using static but looking at your comment, you do not know what it is. Then you are going to start using static all over the place and nothing will work as expected. Give yourself a challenge and a favor, learn how to use GetComponent and learn what static really does.
Static does not mean "Easy to access between script".
+All of the thumbs to @fafase. The static
keyword look so tempting for beginners to use since it seems to solve a recurring problem (exchange data or messages between two objects). However, this keyword can cause a lot of problems further down the road. It should not be used as a means to send data from one object to another. It can be used to share a common set of data among multiple instances.
I think within the context of what you currently are doing, it could make sense to use static
since I presume that even if you had several PlayerAI scripts in the scene, they would all use the same tilemap - correct?
However as @fafase points out, if you are unsure of what static means, you'd do yourself a favor if you figure it out sooner than later. It doesn't mean that you have to rewrite everything and feel hopelessly lost. You can still use static (but be prepared it may bite you softly or very hard). And I think the best way to learn when static is unfriendly is when you actually hit a problem with it. The "danger" then is how you solve that problem, so you don't choose a solution that may involve even more statics. In most cases, using a non-static member is a better approach.
Your answer
Follow this Question
Related Questions
Find GameObjects with a true boolean and put them in an array? 1 Answer
Using getcomponent with an array 2 Answers
Need an advise, how to find all objects with a specific name and a specific script? 2 Answers
Multiple Cars not working 1 Answer
Retrieve an integer from an array in a different script 1 Answer