- Home /
Modify a variable between namespaces
Hi everyone. My question is simple, and I suppose the answer is simple, but I haven't found out the solution yet. I'm using Unity 5.0.2 and doing some practices with the new first person controller. I would like to access other script's variables from this script, but as this controller is into a namespace, It does not find the other script, that has no namespace... If I try to access the controller from another script I just have to put the complete namespace and it works.
How could I access the variable of another script from the controller?
Thanks.
Answer by JC_SummitTech · Mar 23, 2017 at 10:28 PM
If I understand correctly, what you want is to access a variable/function form another MonoBehaviour. any member that is not static won't be accessible unless you have access to an instance of the Monobehaviour. If the other script is in the same gameObject as the CharacterController, you cna access the instance by calling YourClassName myInstance = GetComponent(); then myInstance.MyPublicProperty;
Wow that worked, this helped me create a working difficulty system for my pong game. Thanks!
Answer by TD10074405 · Mar 13, 2015 at 05:05 PM
Try creating an instance of the other file i.e
public class TestClass : MonoBehaviour {
public ClassIWant EasyNameToFind;
public void SomeFunction(){
EasyNameToFind.TheFunctionYouWant();
or
EasyNameToFind.SomeVariable = TheModifiedValue;
}
}
That should be a simple enough way to do it, if I'm understanding you correctly. The "EasyNameToFind" class would then show up in the inspector of your class you're accessing it from, aslong as the Class You want is Serialized
I can do that just to call a function of CharacterController.cs, but I'd like to call a function of weaponScript.cs from CharacterController.cs, I don't know if you understand me...
CharacterController.cs
namespace UnityStandardAssets.Characters.FirstPerson
{
public class FirstPersonController : $$anonymous$$onoBehaviour
{
int number = 0;
//I wanna call here a function from the following script
void SomeFunction(){}
}
}
WeaponScript.cs
public class WeaponScript : $$anonymous$$onobehaviour{
void DoSth()
{
}
}
Although, I can call a function of CharacterController.cs from WeaponScript.cs.
I hope it's more understandable like this.
Thanks a lot.
How to do the other way round? i.e. access the variables of WeaponScript inside FirstPersonController