- Home /
How to use a variable from one file in another? C#
Hello,
I have 2 files, character.cs and a controller.cs
character.cs contains
public bool charCanFly = true;
public float charFlySpeed = 10f;
And I need to access these 2 variables from controller.cs I read somewhere either making them static or referencing them, but I am rather new to C# and I am not entirely sure which method is better and if referencing, then I am not entirely sure how to.
Is it overall good or bad to use stuff from one file in another one?
Thanks
Answer by Jesse Anders · Jan 22, 2011 at 01:34 PM
Is it overall good or bad to use stuff from one file in another one?
It's just fine. (Although it's not so much files that are of interest here, but rather classes/structs.)
Also, read this.
Is it really good or fine? I've found that code becomes harder to work when scripts have to use each others' variables; you have to know what more scripts do that the one you're currently looking at. Do you have any good articles on advanced practices with interdependent classes? Using events has helped my encapsulation a lot, but there are probably lots of methods I've never heard of.
Sure, all the usual guidelines of good object-oriented design apply here (loose coupling, encapsulation, etc.). But, I'd certainly recommend this sort of coupling over, say, the use of static member data (which the OP asked about). $$anonymous$$essaging certainly reduces coupling further, but messaging and direct inter-class communication are different tools with different characteristics, and each has its place (I$$anonymous$$O). But, you're certainly right that decoupling is generally a good thing.