- Home /
Passing a class instance to a method
I'm not a programmer so sometimes I miss very simple things, I feel like this is one of those times.
I'm trying to create a new FrontsData in DataClass and pass it to a method in another class called Fronts that will add it to a dictionary in the Fronts class.
This is just for testing and simplified, the real creation of FrontsData will later be based on user input.
public class DataClass : MonoBehaviour
{
public static DataClass DataClassInstance;
public static Fronts FrontsInstance;
void Awake()
{
DataClassInstance = this;
FrontsInstance = new Fronts();
}
void Start()
{
var testObj = new FrontsData(){frontName = "Hello"};
FrontsInstance.FrontAddChange(testObj);
Debug.Log(JsonConvert.SerializeObject(FrontsInstance)); // Not relevantfor question
}
}
public class Fronts
{
Dictionary<string, FrontsData> FrontDictionary;
public void FrontAddChange(FrontsData x)
{
FrontDictionary[x.frontName] = x;
}
}
public class FrontsData
{
public string frontName;
}
frontName is in the class FrontsData so refrencing x.frontName should get the varible in the instanced FrontsData.
Answer by Alanisaac · May 11, 2018 at 10:20 PM
Looks like your FrontDictionary
is never initialized. Try this in your Fronts class:
public class Fronts
{
Dictionary<string, FrontsData> FrontDictionary = new Dictionary<string, FrontsData>();
public void FrontAddChange(FrontsData x)
{
FrontDictionary[x.frontName] = x;
}
}
Perfect, I thought it would be something simple like this, thanks!
Your answer
Follow this Question
Related Questions
Using method from main class in custom class 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers