Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question Same script but unique variable

Discussion in 'Getting Started' started by Chefspatz, Aug 19, 2022.

  1. Chefspatz

    Chefspatz

    Joined:
    Jul 6, 2022
    Posts:
    2
    Hi, I hope you can help me.

    I have two GameObjects (A and B) with the same function like:

    int clicks = 0;
    public GameObject myGameObject;


    void Update()
    {
    if (Input.GetMouseButtonDown(0))
    {
    clicks++;

    if(clicks >= 5)
    {
    myGameObject.SetActive(false);
    }
    }
    }

    When I click GameObject-A 5 times, both GOs will dissappear, because they share the same variable "clicks". And this is my problem. I don't want that they share the variable. Every single GO must have its own variable. This is not a problem with two GOs, but I want to have much more.

    When I have 300 GameObjects with the same function, how can I handle this? Must I create 300 scripts with 300 unique variables?

    My solution is a GameObject with a 2D-Array and some for-loops or something like this but perhapes there is a better und faster way. :)
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    The issue is because of how you're using
    Input.GetMouseButtonDown()
    .
    This method doesn't check if the mouse was clicked on any specific GameObject, just that the mouse was clicked in general.
    So all of your different instances will detect the same mouse click and each update their own
    clicks
    variables.

    You need to isolate
    Input.GetMouseButtonDown()
    into a separate script/utility that can determine which object was clicked, likely using raycasts to do so.
     
    KindredKara, Chefspatz and Ryiah like this.
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,819
    You've misunderstood what's going on. Different instances of this script don't share the "clicks" variable. Unless you declare it static (which you have not done), every instance gets its own unique copy of that variable with its own value.

    Your test is invalid because you aren't checking what GameObject is being clicked. The script is simply checking whether the mouse button is down. Obviously it is down for all GOs at the same time (you have only one mouse, after all). So the counter is going up in all of them at once — not because they are sharing the variable, but just because they're all doing the same thing.

    EDIT: Ninja'd by @Vryken. :)
     
    Chefspatz and Ryiah like this.
  4. Chefspatz

    Chefspatz

    Joined:
    Jul 6, 2022
    Posts:
    2
    Oh man... I love you! Thank you for these nice answers. Now I understand the issue and can do it better. :) What a bad mistake... argh.