currently I am working on an inventory system I have a list in one script but I’ve looked everywhere possible to find a way to just access the list in another script.
I’ve tried get component but I keep getting errors no matter which way I code it .Ive also tried making the list static but that didn’t work. Is there any hints or tips on what I should do?
For example’s sake, I’ll use names “Script1” and “Script2”. Say Script1 has your list, Script2 is attached to the same GameObject as Script1, and you want to access Script1’s list from within Script2. Here’s a C# example put pretty simply.
//Script1.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Script1 : MonoBehaviour
{
//Be sure you set your List public so that it can be accessed by other classes.
public List<string> testList = new List<string>();
void Start()
{
testList.Add ("Item 1");
testList.Add ("Item 2");
testList.Add ("Item 3");
}
}
//Script2.cs
using UnityEngine;
using System.Collections;
public class Script2 : MonoBehaviour
{
Script1 s1;
//I'm using a coroutine to be sure the list in Script1 is created before I print the items in the list.
IEnumerator Start()
{
s1 = GetComponent<Script1>();
yield return new WaitForEndOfFrame();
foreach(string s in s1.testList)
print (s);
}
}