Sunday, October 15, 2017

Different ways of disabling game object/component in Unity via scripting

Example: HingeJoint2D. When the spacebar is pressed, the object/component is disabled.

1. To disable the entire game object, you can use Destroy. Make sure to tag the appropriate game object.
      private GameObject joint;  
   
      void Start(){  
           joint = GameObject.FindWithTag("joint");  
      }  
   
      void Update() {  
           if (Input.GetKeyDown ("space")) {  
                Destroy(joint);
           }  
      }  

2. To deactivate the game object, use SetActive(false)
      private GameObject joint;  
   
      void Start(){  
           joint = GameObject.FindWithTag("joint");  
      }  
   
      void Update() {  
           if (Input.GetKeyDown ("space")) {  
                joint.SetActive(false);
           }  
      }  

3. Use GetComponent to disable only the HingeJoint2D component, and not the entire game object.
      private HingeJoint2D hinge;  
   
      void Start(){  
           hinge = gameObject.GetComponent(typeof(HingeJoint2D)) as HingeJoint2D;  
      }  
   
      void Update() {  
           if (Input.GetKeyDown ("space")) {  
                hinge.enabled=false;  
           }  
      }  

No comments:

Post a Comment