- Home /
Scaling code to take in variables without using reflection... How to do it?
So lets say I have a script called GameManager and one called Ball. I instantiate GameManager onto one object in my scene, and a bunch of GameObjects with Ball, each behaving differently.
I want ball to change a variable in GameManager (like blueBallDead for example to check to see if a specific ball is disabled), but since (the only way I know how to) add more variables to GameManager is actually hardcoding more in. So if I want to add a new object in my scene that uses Ball in a modular way, I keep having to go back to hardcode more functionality and longwinded if statements into my manager.
Better way to approach this? The only semi-helpful thing I've found was just adding variables into the manager and using reflection on ball in a way where I pass in the variable name as the name of the ball or something, that way I don't have to keep changing ball around. But reflection sucks and is pretty slow.
Answer by crohr · May 28, 2015 at 02:03 AM
public class GameManager
{
private static Dictionary<string, Ball> _balls = new DictionaryBase<string, Ball>();
public static void AddBall(Ball ball)
{
if(!_balls.ContainsKey(ball.Id))
{
_balls.Add(ball.Id, ball);
}
}
}
public class Ball
{
public string Id;
public bool IsAlive;
void Start()
{
GameManager.AddBall(this);
}
}
With a Dictionary you can add new Ball types easily.
Thanks, surprised you were able to figure out what I was after. Appreciate the detailed and quick response, got what I needed up and running quick enough.
So I basically just write a few more methods to get data by feeding in a string argument that'll match the ID(key) of the entry in the dictionary, yeah? 'Least that's how I got it working. I forgot how useful static was too, making me able to call this stuff without an explicit reference to an instance of the levelmanager since they'd all be using the same static data.
Is the purpose of dictionary basically to be a List/Array but tying together entries with ID keys?
Sorry for the super noob questions, I've been coding for a few years now casually but I've been using pretty basic methods of getting what I need done. :P
You can add a GetBall(string id) and RemoveBall(string id). I guess what I was imagining in my head when I read your question was you would have several different ball prefabs, each one having a unique Id set in the inspector.
A Dictionary is an indexed collection of $$anonymous$$eyValuePairs (Basically a map from the key to the value.) Accessing a value by key is much faster than iterating through an Array or List.
There is no such thing as a "super noob" question :P as long as you are trying to learn.
Good luck with you project!