Home > Enterprise >  Why doesn't the incremental function work?
Why doesn't the incremental function work?

Time:12-12

I just want to make an operation available two times. For example:

I press 5 on the keyboard and Object1 is instantiated but, at the same time, the counter is increased by one. After this, I press 5 again, the Object1 is instantiated again, the counter is increased by one again. So, this time, if I try to press 5 for a third time, nothing happens.

Should be easy right? That's what I thought and I still think that it should be this easy but, every time i press 5, the Object1 is instantiated and the counter doesn't increase. To be more specific, the counter increase for a moment and after that instant, it resets to 0.

public class Placement : MonoBehaviour
{
    public GameObject Object1;
    private int count = 0;

    void Start()
    {

    }

    void Update()
    {
        Debug.Log(count);
        if ((Input.GetKeyDown(KeyCode.Alpha5)) && count < 2)
        {
            count = count   1;
            Instantiate(Object1, transform.position, transform.rotation);
            this.enabled = false;
        }
    }
}

I simplified the code just to get straight to the point. Through the console (debug) I saw that the count is automatically reset to 0 at each cycle...

CodePudding user response:

According to your code logic, you will disable the Object after pressing 5. You probably want to disable it after 2 presses.

if ((Input.GetKeyDown(KeyCode.Alpha5)) && count < 2)
{
    count = count   1;
    Instantiate(Object1, transform.position, transform.rotation);
    if(count >= 2) {
        this.enabled = false;
    }
}

The reason it appears, that your counter doesn't increase at all is this: You log count but then disable it after pressing 5, so no more logs will happen in Update().

Tip: You could make count public or use [Serializable], OR use the debug-inspector view to see the actual value of count, instead of relying on the Debug.Log.

edit: If Object1 has the Placement script attached, you are creating more and more scripts (with a count variable each).

It's best to have a manager object that instantiates other objects. But you can also remove/disable the script on the instantiated objects like this:

if ((Input.GetKeyDown(KeyCode.Alpha5)) && count < 2)
{
    count = count   1;
    GameObject newObj = Instantiate(Object1, transform.position, transform.rotation);


    newObj.getComponent<Placement>().enabled = false; // this disables the script

    // (optional) Destroy(newObj.getComponent<Placement>()); // this removes the script
    

    if(count >= 2) {
        this.enabled = false;
    }
}
  • Related