Search Unity

Disable script from other script

Discussion in 'Scripting' started by Pandzas, Jul 15, 2021.

  1. Pandzas

    Pandzas

    Joined:
    Sep 30, 2020
    Posts:
    10
    So i have two scripts on the same gameobject and i want to disable one script from the other. I found some people saying i can use
    Code (CSharp):
    1. GetComponent(scriptname).enabled = false;
    but it doesnt work for me same with
    Code (CSharp):
    1. GetComponent<scriptname>().enabled = false;
    any ideas on why this is happening?
     
  2. TheFunnySide

    TheFunnySide

    Joined:
    Nov 17, 2018
    Posts:
    200
    I hope scriptname is the name of the class. It should work.
    Alternatively you can just save a reference to the script somewhere and call enabled on that.
    (Thats also the recommended that)
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    This one is correct:
    Code (CSharp):
    1. GetComponent<scriptname>().enabled = false;
    But it only works if a few things are true:
    -
    scriptname
    is the class name of the script you're trying to get. i.e. it looks like
    public class scriptname : MonoBehaviour

    - Both the
    scriptname
    script and the script this code is in need to be attached to the SAME GameObject.
     
  4. Pandzas

    Pandzas

    Joined:
    Sep 30, 2020
    Posts:
    10
    The script i wanna disable has VersionedMonoBehaviour instead of just MonoBehaviour, is that maybe the reason?
     
  5. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Explain what you mean by "doesn't work". If you are getting an error, post the error.

    What is a VersionedMonoBehaviour?
     
  6. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    No that's most likely not the reason. What exactly is going wrong? We're not mind readers.
     
  7. Pandzas

    Pandzas

    Joined:
    Sep 30, 2020
    Posts:
    10
    Ok, my bad. So the error when i use
    Code (CSharp):
    1. GetComponent<name>().enabled = false;
    is that it says "The type or namespace name could not be found". When i use
    Code (CSharp):
    1. GetComponent(name).enabled = false;
    the error is "Component' does not contain a definition for 'enabled' and no accessible extension method 'enabled' accepting a first argument of type 'Component' could be found (are you missing a using directive or an assembly reference?)"
     
  8. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Code (CSharp):
    1. GetComponent<name>().enabled = false;
    2.  
    You have to replace 'name' with the name of your script.