How to commuunicate scripts form default namespace?
Hi, I got a problem. How to take values form script One to script Two, when the first script is in different namespace? I mean i got something just like this (let's say it is so short) first script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptOne : MonoBehaviour
{
public float iWantThisVariableInAnotherScript;
}
And I want to have an access to this variable in another script (it's ready script in Unity - FirstPersonController, so I guess all of you know that script). And it looks like:
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
AND HERE, HOW TO GET ACCESS TO MY public float iWantThisVariableInAnotherScript ??
}
}
I am sorry for my spelling mistakes, be permissive :) I'm waiting for Your responses.
Answer by Determined · May 01, 2017 at 04:39 PM
As far as I know, cleanest way to do this is to put your script in a namespace.
Then use that namespace in the script where you want to access the variable.
So, the first script can be like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MyNamespace
{
public class ScriptOne : MonoBehaviour
{
public float iWantThisVariableInAnotherScript;
}
}
After that, you can access the variable in 2nd script like this:
using MyNamespace;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
//AND HERE, HOW TO GET ACCESS TO MY public float iWantThisVariableInAnotherScript ??
//You can access the variable now
}
}
Yep, it's working. Only thing is that I need to put both scripts in same folder. It is not working in different ways, I'm not sure if it's fully correct.
Oh. I forgot about that. You are right. Scripts inside standard assets folder, compiles before the scripts in other folders. That's why it can't find $$anonymous$$yNamespace.
What to do if I don't want a namespace for my first class but still want to access that first class from an other namespaced class ?
@DomeCreator You can't. Unless you upgrade to version 2020.2, where they finally (after ~14 years) added a root namespace: https://unity3d.com/unity/whats-new/2020.2.0