0
\$\begingroup\$

I am currently working on 2D platform game. The following script adding the child objects inside the array and identifies the child object I click on and checks the tag on it. Now I don't know how to disable the child object that I have clicked and I want the disabled child object to be re-enable when I click on another child object inside the same parent object. Any help would be appreciated.

public class SelectedPlatform : MonoBehaviour {

    public GameObject platform;
    void Start()
    {
        Transform[] children = new Transform[transform.childCount];
        for (int i=0; i<transform.childCount; i++) 
        {
            children[i]=transform.GetChild(i);
        }
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
         {
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

            if(hit.collider.gameObject.tag == "Platform")
            {
                Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
            }   
         }
    }
}
\$\endgroup\$
1
\$\begingroup\$

I'd be tempted to handle this with two scripts:

// Put this on each container object:
public class ToggleableContainer : MonoBehaviour {

    ToggleableItem _currentSelection;

    // On initialization, find all toggleable children of this parent.
    void Start() {
       ToggleableItem[] children = GetComponentsInChildren<ToggleableItem>();
       // Let each child know who to talk to when they're clicked:
       foreach(var child in children)
           child.SetContainer(this);
    }

    // When one platform is clicked, disable it and re-enable the last selection (if any).
    public void Select(ToggleableItem target) {
       if(target == _currentSelection)
          return;

        if(_currentSelection != null)
            _currentSelection.gameObject.SetActive(true);

        if(target != null)
            target.gameObject.SetActive(false);

        _currentSelection = target;
    }    
}

.

// Put this on each platform object you want to toggle between enabled/disabled:
public class ToggleableItem : MonoBehaviour {

    ToggleableContainer _container;

    // Allow the parent container to register itself.
    public void SetContainer(ToggleableContainer container) { 
        _container = container;
    }

    // For simple click interactions, Unity will handle the raycasting for you
    // if you just implement a method to respond to the "OnMouseDown" message.
    void OnMouseDown() {
        // Tell our container we've been selected - it will handle coordinating the rest.
        if(_container != null)
             _container.Select(this);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.