- Home /
 
 
               Question by 
               Its_Thomas · Oct 17, 2017 at 07:48 PM · 
                scripting problemradiusbreak  
              
 
              How can i make a object break when i am in range with the object, while holding another object in hand?
I am having a Crate in my scene and i have also a cracked_Crate. I want to make the Crate break when i am in a radius of 2f (i already have a script that says to change crate for cracked crate while i click it) but if i set a radius on it . It wont work, so my question is can any one help me to make the crate only break while holding my axe in my hand?
 using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class Destructible : MonoBehaviour {
  
  
      public GameObject destroyedVersion;
  
      void OnMouseDown ()
      {
          Instantiate(destroyedVersion, transform.position, transform.rotation);
          Destroy(gameObject);
  
      }
  
  }
 
              
               Comment
              
 
               
              Answer by StormMuller · Oct 17, 2017 at 08:52 PM
 public class ObjectBreaker : Monobehaviour
 {
     public Transform[] breakables;
     public Transform player;
     public GameObject destroyedVersion;
     public float distanceCanBreakObject = 2f;
     
     private float sqrLen;
     
     void Start()
     {
         sqrLen = distanceCanBreakObject * distanceCanBreakObject;
     }
     
     void Update ()
     {
         if (Input.GetMouseButton(0) && hasAxeInHand)
         {
             foreach (breakable in breakables)
             {
                 var offset = breakable.position - player.position;
                 var sqrLen = offset.sqrMagnitude;
                 
                 if (sqrLen < this.sqrLen)
                 {
                     Instantiate(destroyedVersion, breakable.position, breakable.rotation);
                     Destroy(breakable);
                 }
             }
         }
     }
 }
 
               Have a list of creates
Listen for a click
When clicked destroy all creates in radius (calculated using squared Magnitude)
You could replace Input.GetMouseButton(0) with Input.GetMouseButtonDown(0) if you want the player to spam his/her mouse button :)
https://docs.unity3d.com/ScriptReference/Vector3-sqrMagnitude.html
Your answer