Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Disabling a script through code!

Discussion in 'Scripting' started by SP-Designs, Jul 11, 2016.

  1. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    Hey there.I need to disable a script when i press escape and i want this to happen through another script obviously.My problem is that i do not know how to actually make a reference to it and access it's setActive function.I tried looking it up online but did not manage to understand it and make it work.If you think you can help me,please post a reply below,it would help me a lot with my game.Thanks in advance!
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,384
    Use GetComponent<T>(); on the host GameObject which will store a reference to the script of <T>.

    So something like...

    Code (csharp):
    1. MyClass theScriptWanted = targetGameObject.GetComponent<MyClass>();
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,146
    If you're using SetActive, you want to assign it to a GameObject variable. You can either do this through drag and drop in the inspector, GameObject.Find, or some other way.
    If you're using Enabled, you want to do what LaneFox suggested.
     
  4. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    The myClass part is the type right?It does not let me use that...do i need to put something in front of it to specify that this is a custom type of variable?
     
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,146
    myClass is a placeholder for the component name. Like image, or text, or playerData (name of your script). you have to replace it with whatever you are using.
     
  6. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    this is what i wrote : FPSScript First_Person_Controller = FPS.GetComponent<FPSScript>(); but it gives me an error for the FPSScript placeholder!
     
  7. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    fyi, if you find yourself saying that, it really really needs to be followed up with a paste of the error :p :)
     
    Kurt-Dekker likes this.
  8. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    The type or namespace you are using "FPSScript" could not be found. <-- this is the error :D
     
  9. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Checklist:

    - Are you SURE it's named "FPSScript" and not "FpsScript" or "FPS_Script"?
    - It needs to be a MonoBehaviour ( public class FPSScript : MonoBehaviour )
    - FPSScript needs to be in a file with the same name as the class ( FPSScript.cs )
    - If it's in a namespace (namespace Whatever in FPSScript.cs), you need to put "using Whatever" for the namespace in the script you're referencing it from.
     
    Kurt-Dekker likes this.
  10. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    it is name : First Person Controller just like that, but what do i do with the blank space?can i like add underscores to fill them in cause i don't think that such a script name can be taken for a namespace by unity.
     
  11. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    I mean the name of the class in the FPSScript.cs file, not the name of the GameObject in the scene.
     
  12. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,384
    GetComponent requires a class name, not a variable name. It's just like the example.
     
  13. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    I figured out that i don't actually need to disable a script but a component of the FPS GameObject in my scene which however isn't available when i do FPS.GetComponent<nameofthatcomponent>();

    *As for the script that i wanted to make a reference to,i also found out that it is not using MonoBehaviour but the namespace

    Code (csharp):
    1. namespace UnityStandardAssets.Characters.FirstPerson
    and is using the following :
    Code (csharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityStandardAssets.CrossPlatformInput;
    4. using UnityStandardAssets.Utility;
    5. using Random = UnityEngine.Random;
    so i guess i would need to use those things too in order for the namespace to become available right?

    Below i added a picture of the first person controller component that i want to de-activate but can't find it through scripting(i noticed that it has a script icon on the left,does that mean that it was created by a script or something?)

    ** Sorry if i make too many questions and most of them are stupid but i am an amateur programmer yet so i need to learn more and these problems help me a lot when i get help from more experienced programmers on the forums so thanks for your help so far ;) ! Capture.PNG
     
  14. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,146
    There is no using.monobehavior...

    It's inherited, so it will be with the class name
    public class myClass : MonoBehaviour

    As far as your script, it's called FirstPersonController. So you use getComponent<FirstPersonController>()
     
  15. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Ohhhh it's the Standard Assets one. Well yeah you need two things, at the top of your file:

    Code (csharp):
    1. using UnityStandardAssets.Characters.FirstPerson;
    And then where you want to get the component:

    Code (csharp):
    1. FPS.GetComponent<FirstPersonController>();
     
  16. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    Awesome i managed to make the reference but i am having trouble disabling it when i press Escape.
    I tried doing :

    Code (csharp):
    1.  private Component scriptToDisable;
    2. scriptToDisable = FPS.GetComponent<FirstPersonController>();
    3.  
    4. ...(code for when i press escape)... {
    5.   .....
    6. // I tried the following :
    7. scriptToDisable.gameObject.SetActive(false);
    8. // before defining the scriptToDisable component i tried
    9. FPS.GetComponent<FirstPersonController>().enabled = false;
    10.   .....
    11. }
    I couldn't find a way to make this work though.I searched on the unity documentation and videos but i saw only parts of code doing somehting like !scriptToDisable.enabled; .Any suggestions?
     
  17. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Either of those methods should work... the first will disable the entire game object and everything on it, the same as unchecking the checkbox at the top of the inspector (so if there's a camera attached, it will disable that, maybe not what you want). The second will disable only the FPS controller, the same as unchecking the checkbox next to First Person Controller in the inspector.

    I'd guess something's wrong with "code for when I press escape". It needs to be in the Update() method. I'd really suggest going through some of the intro tutorials on Unity's site before going too much further, since they explain how to do all of these common things better than I'd be able to.
     
  18. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    This is the code i am using right now :
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4. using System.Collections;
    5. using UnityStandardAssets.Characters.FirstPerson;
    6.  
    7. public class PauseManager : MonoBehaviour {
    8.    public GameObject pausable;
    9.    public Canvas pauseCanvas;
    10.  
    11.    private bool isPaused = false;
    12.    private Animator anim;
    13.    private Component[] pausableInterfaces;
    14.    private Component[] quittableInterfaces;
    15.   public GameObject FPS;
    16.  
    17.   void Start()
    18.    {
    19.      // PauseManager requires the EventSystem - make sure there is one
    20.      if (FindObjectOfType<EventSystem>() == null)
    21.      {
    22.        var es = new GameObject("EventSystem", typeof(EventSystem));
    23.        es.AddComponent<StandaloneInputModule>();
    24.      }
    25.  
    26.      pausableInterfaces = pausable.GetComponents (typeof(IPausable));
    27.      quittableInterfaces = pausable.GetComponents (typeof(IQuittable));
    28.      anim = pauseCanvas.GetComponent<Animator> ();
    29.  
    30.      pauseCanvas.enabled = false;
    31.  
    32.   // CHECK ME OUT
    33.   FPS.GetComponent<FirstPersonController>();
    34.   }
    35.    
    36.    void Update () {
    37.      if (Input.GetKeyDown(KeyCode.Escape))
    38.      {
    39.        if( isPaused ) {
    40.          OnUnPause();
    41.   // Over here
    42.   FPS.GetComponent<FirstPersonController>().enabled = true;
    43.   } else {
    44.          OnPause();
    45.   // Check me out too
    46.   FPS.GetComponent<FirstPersonController>().enabled = false;
    47.   }
    48.      }
    49.  
    50.      pauseCanvas.enabled = isPaused;
    51.      anim.SetBool( "IsPaused", isPaused );
    52.    }
    53.      
    54.    public void OnQuit() {
    55.      Debug.Log ("PauseManager.OnQuit");
    56.  
    57.      foreach (var quittableComponent in quittableInterfaces) {    
    58.        IQuittable quittableInterface = (IQuittable)quittableComponent;
    59.        if( quittableInterface != null )
    60.          quittableInterface.OnQuit ();
    61.      }    
    62.    }
    63.    
    64.    public void OnUnPause() {
    65.      Debug.Log ("PauseManager.OnUnPause");  
    66.      isPaused = false;
    67.  
    68.      foreach (var pausableComponent in pausableInterfaces) {    
    69.        IPausable pausableInterface = (IPausable)pausableComponent;
    70.        if( pausableInterface != null )
    71.          pausableInterface.OnUnPause ();
    72.      }
    73.    }
    74.  
    75.    public void OnPause() {
    76.      Debug.Log ("PauseManager.OnPause");
    77.      isPaused = true;
    78.  
    79.      foreach (var pausableComponent in pausableInterfaces) {    
    80.        IPausable pausableInterface = (IPausable)pausableComponent;
    81.        if( pausableInterface != null )
    82.          pausableInterface.OnPause ();
    83.      }
    84.    }
    85. }
    But i get an error :
    NullReferenceException: Object reference not set to an instance of an object
    PauseManager.Update () (at Assets/PauseController/Scripts/PauseManager.cs:45).Why won't this work?The First Person Controller component does not get de-activated when it has to so,do i need to create a gameObject or Component variable and set it equal to FPS.GetComponent<FirstPersonController>().enabled; ?(cause i've tried this already like i said previously).
     
  19. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    You need to drag and drop the FPS object onto the "FPS" field in the inspector.
     
  20. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,739
    SetActive applies to gameObjects not scripts / components. To get reference to a component, you click and drag via the inspector, or use GetComponent<T>(), to enable or disable a script, you set its .enabled property.

    Keep in mind that setting enabled to false, only prevents it from receiving messages from unity like update or OnCollsionEnter, and does not prevent other scripts from calling its public methods, or changing its public properties.
     
  21. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    How should i use the .enabled property to disable the script not just stop it form receiving messages from unity?Because from the unity tutorials that i've watched they use it to disable and enable objects and lights but i cannot get it to work with this component.Is there another property that i can use?
     
  22. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    I've done this before i wrote any line of code ;) !
     
  23. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,739
    well that should be enough, but if you need extra stuff to happen, add a OnEnable and a OnDisable method to add logic you want to run when the object gets enabled or disabled. If you want it to ignore all public method calls, just make a if statement that checks if its enabled, and returns early if disabled.
     
  24. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    The only thing i want to happen is to get the First Person Controller component of the FPS game object to get unchecked but using the code that i posted above,this does not happen for some reason and the error that i posted also above does not make it any easier for me.Any other ideas?Should i post the script in which i added the code?
     
  25. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    I am a bit confused here,i want to disable the First Person Controller component but from what i can understand from my code,i am accessing the script FirstPersonController.However the First Person Controller component has a script icon on the top-left,what does that mean?Can i somehow access that kind of component through my script and disable it?
     
  26. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,384
    All Monobehaviors are components. When you add a script to a GameObject, it is a component on that GameObject.

    When you do this:
    Code (csharp):
    1. FirstPersonController MyController = MyCharacterGameObject.GetComponent<FirstPersonController>();
    You are grabbing that component from the inspector and putting it as a reference into the "Controller" variable. If you disable it, it will stop working. Thats all there is to it.
     
  27. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    man i am doing this exact thing but i keep on getting this same error over and over again which does not help me figure out the issue :
    NullReferenceException: Object reference not set to an instance of an object
    PauseManager.Update () (at Assets/PauseController/Scripts/PauseManager.cs:48)

    Here is the script i am using again :

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4. using System.Collections;
    5. using UnityStandardAssets.Characters.FirstPerson;
    6.  
    7. public class PauseManager : MonoBehaviour {
    8.    public GameObject pausable;
    9.    public Canvas pauseCanvas;
    10.  
    11.    private bool isPaused = false;
    12.    private Animator anim;
    13.    private Component[] pausableInterfaces;
    14.    private Component[] quittableInterfaces;
    15.   public GameObject FPS;
    16.   FirstPersonController myController;
    17.  
    18.   void Start()
    19.    {
    20.      // PauseManager requires the EventSystem - make sure there is one
    21.      if (FindObjectOfType<EventSystem>() == null)
    22.      {
    23.        var es = new GameObject("EventSystem", typeof(EventSystem));
    24.        es.AddComponent<StandaloneInputModule>();
    25.      }
    26.  
    27.      pausableInterfaces = pausable.GetComponents (typeof(IPausable));
    28.      quittableInterfaces = pausable.GetComponents (typeof(IQuittable));
    29.      anim = pauseCanvas.GetComponent<Animator> ();
    30.  
    31.      pauseCanvas.enabled = false;
    32.  
    33.   // CHECK ME OUT
    34.   myController = FPS.GetComponent<FirstPersonController>();
    35.   }
    36.    
    37.    void Update () {
    38.      if (Input.GetKeyDown(KeyCode.Escape))
    39.      {
    40.        if( isPaused ) {
    41.          OnUnPause();
    42.   // Over here
    43.   //FPS.GetComponent<FirstPersonController>().enabled = false;
    44.   myController.enabled = true;
    45.   } else {
    46.          OnPause();
    47.   // Check me out too
    48.   //FPS.GetComponent<FirstPersonController>().enabled = true;
    49.   myController.enabled = false;
    50.   }
    51.      }
    52.  
    53.      pauseCanvas.enabled = isPaused;
    54.      anim.SetBool( "IsPaused", isPaused );
    55.    }
    56.      
    57.    public void OnQuit() {
    58.      Debug.Log ("PauseManager.OnQuit");
    59.  
    60.      foreach (var quittableComponent in quittableInterfaces) {    
    61.        IQuittable quittableInterface = (IQuittable)quittableComponent;
    62.        if( quittableInterface != null )
    63.          quittableInterface.OnQuit ();
    64.      }    
    65.    }
    66.    
    67.    public void OnUnPause() {
    68.      Debug.Log ("PauseManager.OnUnPause");  
    69.      isPaused = false;
    70.  
    71.      foreach (var pausableComponent in pausableInterfaces) {    
    72.        IPausable pausableInterface = (IPausable)pausableComponent;
    73.        if( pausableInterface != null )
    74.          pausableInterface.OnUnPause ();
    75.      }
    76.   //FPS.GetComponent<FirstPersonController>().enabled = false;
    77.   }
    78.  
    79.    public void OnPause() {
    80.      Debug.Log ("PauseManager.OnPause");
    81.      isPaused = true;
    82.  
    83.      foreach (var pausableComponent in pausableInterfaces) {    
    84.        IPausable pausableInterface = (IPausable)pausableComponent;
    85.        if( pausableInterface != null )
    86.          pausableInterface.OnPause ();
    87.      }
    88.   // FPS.GetComponent<FirstPersonController>().enabled = true;
    89.   }
    90. }
    91.  
    I don't get why it is not working(and in case you ask too,yes i do have assigned the required gameObject to the FPS space in the inspector). :D ;(
     
  28. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,384
    Why are all of those lines commented out?
     
  29. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    because they did not work!
     
  30. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,384
    If the GameObject FPS is not null, then FPS doesn't have a FirstPersonController script on it. That's what null reference means, something in that line is null and it cannot be.
     
  31. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    If you really can't figure out which is null, you can separate it into multiple lines and use Debug.Log to figure it out:
    Code (csharp):
    1. if(FPS == null) Debug.LogError("FPS is null! Make sure you drag the FPS object onto the inspector");
    2. var fpsController = FPS.GetComponent<FirstPersonController>();
    3. if(fpsController == null) Debug.LogError("fpsController is null! Make sure there is a FirstPersonController script attached to FPS!");
    4.  
     
  32. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    That did actually help, i get the 3rd error : fpsController is null so that means that there is not FirstPersonController script on my Fps gameobject.Hmmm,however,in the image below you can clearly see that there is one : Capture.PNG
     
  33. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    And you're sure that object right there is the one you dragged onto the "FPS" slot in the inspector?
     
  34. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    yup double checked!
     
  35. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    I really don't get it, obviously the script is there but the debug.log says there is not!What is going on here??
     
  36. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    can you post a screenshot of the inspector of the gameobject that the "PauseManager" script is attached to.


    technically speaking, until you wrote the code in order to create the field in the inspector you couldn't have... get the impression there are some crosswires going on here...
     
  37. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    Sorry i am taking so long but unity does not work for me right now ;( Gonna reply asap,thanks for your patience!
     
  38. SP-Designs

    SP-Designs

    Joined:
    Oct 13, 2015
    Posts:
    184
    This is it : Capture.JPG
     
  39. Deleted User

    Deleted User

    Guest

    Assets\Scenes\DisabledScr2.cs(19,49): error CS0165: Use of unassigned local variable 'SpriteVisibility'
    gives ,e this error
     
  40. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,365
    @Luca1047 , if you are experiencing some sort of problem then you should create a new forum thread that describes the problem in detail. Do not post on a random 4-year-old thread that has nothing to do with your problem- That's just going to distract people from your post.