How to pass arrays from one object to another?
The arrays are initialized in the inspector as shown below which is attached to the same object ("A") that the "Pathing" script is attached to.
The script ("Pathing") has a function below:
public Transform[] getPath(){
return path;
}
I call the above function in the following script ("PathFollower") which is attached to another gameObject ("B"):
void Start () {
path=other.getPath();
}
However it says the following 2 errors:
NullReferenceException: Object reference not set to an instance of an object
Pathfollower.Start () (at Assets/Pathfollower.cs:16)
How can I get the array from the other gameObject? I would assume that the code will work cos the array for "A" will be initialized at Start and I will be able to pass on the array to "B" to work on. Thanks in advance for any advice!
Answer by ransomink · Aug 29, 2015 at 05:04 PM
It's hard to tell without posting your entire script for Pathing and PathFollower. Displaying the lines for each error (along with the script) helps us better understand the problem; so I'm assuming the errors in question pertain to the code posted above.
Question: How is the variable other declared. Is it a reference to the Pathing script, a GameObject type, another type: int, float, string, etc.? Without the full code we can't tell what it is.
If you know what GameObject you need to grab the array from, simply declare the variable other as a public reference to the Pathing script and drag-and-drop the GameObject inside the inspector, like so:
PathFollower script
using UnityEngine;
using System.Collections;
public class PathFollower : MonoBehaviour {
public Pathing other;
public Transform[] path;
void Start () {
path = other.getPath();
}
}
The variable other will appear inside the inspector on the GameObject using the PathFollower script. As previously stated, just drag-and-drop the GameObject using the Pathing script onto the variable other.
I've just tested this myself and it works. Hope this helps!
Thanks this works! It seems that I need to drag the script onto the variable other.
Answer by hexagonius · Aug 29, 2015 at 03:07 PM
if you do not use code to grab a reference to Pathing for the variable other, show it in the inspector and assign it the Pathing script from object A.
Hi i do use code to grab a reference to pathing. How do i get the reference to the transform array then?
that part is correct, it's just that other is not assigned the Pathing script. your search and assignment post must be wrong. are you using Gameobject.Find, or something else? when is it called?
I am using this`Pathing other`to get reference to the pathing script. Am I doing it wrong?
Your answer
![](https://koobas.hobune.stream/wayback/20220612001900im_/https://answers.unity.com/themes/thub/images/avi.jpg)