FlamingGenius
FlamingGenius

Reputation: 216

Clone Objects opens all UI menus of all the clones

So in unity I have a prefab that contains a canvas

This prefab is instatiated at runtime and can be instantiated multiple times throughout the game

Now lets assume 2 of these prefabs Barracks exist in the game

If I click on Barracks #1

private void OnBarrackClick(){
        if (Input.GetMouseButtonDown (0) && !GameManager.Instance.buildModeActive) {
            RaycastHit hit;
            if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, 25.0f, LayerMask.GetMask ("Barrack"))) {
                this.trainingMenu.SetActive (true);
            }
        }
    }

Then I will get the menus for both Barracks #1 and #2

However I also have an exit button on this UI

public void ExitTrainingMenu(){
        this.trainingMenu.SetActive (false);
    }

This exit function is called through a exit button located on the ui and it exits only the menu for that Barracks while the SetActive function is called through code and displays all the menus

What should be happening is only the UI for the barracks that is clicked should be displaying

How do I fix this bug and whats the cause of it?

To better demonstrate this I have uploaded a video here

http://kot90.altervista.org/survius/display.php?name=IGt6yCrYgV

Upvotes: 1

Views: 56

Answers (2)

Imran Hashmi
Imran Hashmi

Reputation: 61

The cause is already explained by Draco18s but the easiest way to achieve what you want is using

void OnMouseDown()
{
    Debug.Log("OnMouseDown");
    canvasObject.SetActive(true);
}

Note: Make sure a Collider is attached to the gameobject.

Upvotes: 0

You aren't discriminating your clicks against a single building. You're only checking...

  1. Is the mouse down? (this is true for both barracks)
  2. Is GameManager.Instance.buildModeActive false? (this is true for both barracks)
  3. A raycast against a Layer Mask for the "Barrack" layer (this is true for both barracks)

And if all of these things pass, display the UI.

But you have two barracks. Which one was hit? Was it my barracks object or was it some other barracks object?

Upvotes: 2

Related Questions