'Unity fill array Gameobject from another script
I have been follow video from youtube for creating custom tabs. But in condition Iam using dynamic panel, and then in script has to fill panel to array Gameobject objectsToSwap. My Question how I fill that array from another script ? enter image description here
Solution 1:[1]
Let's: -call the script with the Array = A -call the script with the GameObjects = B
You need to get a reference to the script A on the script B.
Then you could do something like this:
public class A : MonoBehaviour
{
private GameObject[] _array;
public void AssignObjects(GameObject[] objects)
{
_array = objects;
// if you're doing this on the editor then you also want to set A as dirty to make sure the changes are saved
// also need to include #if UNITY_EDITOR so this doesn't get compiled on builds
// this can't be compiled because the UnityEditor namespace does not exist on builds
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
}
public class B : MonoBehaviour
{
[SerializeField] private GameObject[] objects;
[SerializeField] private A otherScript;
[ContextMenu("Assign Objects")] // in case you want to do this using the context menu (click the 3 dots on the inspector of this script)
private void AssignObjects()
{
AssignObjects(otherScript);
}
public void AssignObjects(A script)
{
script.AssignObjects(objects);
}
}
Another option if you have access to all those fields in the editor, just right click on the origin array => Copy then right click on the desired array => Paste
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Antônio Pedro |
