Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[HELP] How to disable objects by tag name "Block" using button

Discussion in 'Scripting' started by Goldensnitch, Jan 14, 2017.

  1. Goldensnitch

    Goldensnitch

    Joined:
    Nov 4, 2016
    Posts:
    60
    This is the script far i have done but i am keep getting error can someone help me out please

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CubeEnable : MonoBehaviour {
    6.  
    7. private GameObject cubeObject;
    8.  
    9. void Start()
    10.  
    11. {
    12.     cubeObject = GameObject.FindGameObjectWithTag("Cube");
    13.     Disable();
    14. }
    15.  
    16.  
    17. public void Disable()
    18. {
    19.     cubeObject.SetActive(false);
    20. }
    21.  
    22. public void Enable()
    23. {
    24.     cubeObject.SetActive(true);
    25. }
    26. }


    // THIS IS THE ERROR I AM GETTING IN CONSOLE

    NullReferenceException: Object reference not set to an instance of an object
    CubeEnable.Enable () (at Assets/Scene/Scripts/CubeEnable.cs:25)
     
  2. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    Is this object active in your scene? If it isn't, the Start function won't fire, and cubeObject won't be defined, and the disable and enable functions can't set active something which is not defined.
     
  3. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    How is your hierarchy set up. Is this script you posted on a different GameObject from the cubeObject? If its not, as soon as you SetActive(false) you won't be able to turn it back on since its script doesn't work anymore.

    If they are separate scripts on separate GO's. You disable the cube right off the bat, which doesn't seem to cause an error. What is calling Enable method, a button somewhere? Do you have more than one copy of the CubeEnable script in your scene?