Cannot disable a script from another script?
We are trying to disable the visibility of the menu on a separate script from a different script. We wrote:
public JoshsMenu menuState;
void Start () {
menuState = GetComponent<JoshsMenu> ();
menuState.enabled = false;
}
But we are still getting error: NullReferenceException: Object reference not set to an instance of an object. It stems from the line: menuState.enabled = false; Thank you for tolerating our naiveté.
Answer by Rajeesh_AR · Mar 18, 2016 at 04:41 AM
Here your GetComponent is not valid.
This script JoshMenu is attached to a GameObject... Right ?? And you need to disable the script of that Gameobject.. (assume that the joshMenu attached gameObject is different)
for that you could use,
gameObject.GetComponet< JoshMenu >().enabled = false;
If the JoshMenu script and the current script are attached to the same gameObject, then you may use:
GetComponet< JoshMenu > ().enabled = false;
This answer is inaccurate. Using just GetComponent<Joshs$$anonymous$$enu>();
will work providing that both scripts are attached to the game object. I just checked it myself in Unity to make sure I wasn't going crazy.
I mean, If the scripts are attached to different gameobject
eg:
Public Class script2{
public GameObject go1;
void funct()
{ go1.GetComponent < Josh$$anonymous$$eny> ().enabled = true
}
}
yes, if it's on a different game object, you would have to reference that object, but neither of the examples in the answer refer to a separate game object. They would both only work if the scripts were on the same object. Perhaps you could update your answer to clarify, if that is what you mean.
Thank you for your contribution. We did have it attached to the object, but it was on a different object. After fiddling with assigning variables, it all worked with this:
GameObject.Find("cursor").GetComponent<Joshs$$anonymous$$enu> ().enabled = false;
"cursor" was the object that had the other script "Joshs$$anonymous$$enu" on it.
Answer by kami1339 · Mar 28, 2019 at 12:33 PM
use this
public GameObject otherobj;//your other object
public string scr;// your secound script name
void Start () {
(otherobj. GetComponent(scr) as MonoBehaviour).enabled = false;
}
Thanks so much, I've been looking for something like this for a long time.
Answer by jebemti · Mar 17, 2016 at 11:06 PM
To be able to use GetComponent the script would have to be on the same object that you are calling from.
If you assign the variable in the editor before entering Play mode just remove the line where you try to get it.
Your answer

Follow this Question
Related Questions
Problem with enabling menu 0 Answers
I wan't to check if variable on a scritp component is missing 0 Answers
How to alter Right/Top Value from RectTransform 0 Answers
[Solved] How to find a variable using the value of another variable? 1 Answer
Is it possible to change CustomPass variables via other script? 0 Answers