How to destroy my script thats attached to my game object?

Because I need to have a static variable, the game will always remember how many items you got from one level to the next. So I need to destroy that script each time you get to the exit, so that the item count will reset when you get to the next level.

I have two levels in a row where you must collected a certain amount of the same item, and the same amount each time. But, the game is remembering how much you collected from the previous level so you can just go straight for the exit on the next level which is not supposed to be that way.

Exit Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class ExitToLevel : MonoBehaviour
{
  
public GameObject exitToLevel;

void OnTriggerEnter2D(Collider2D col)

    {
        if (col.name == "Player1")
        {

            if (ItemCollected.itemcollected >= 8)
      
            {
                StartCoroutine("StartDelay");
            }
        }
    }


  IEnumerator StartDelay()  //pauses then after 3 seconds are up, it goes to the next scene
            {
                Time.timeScale = 0;  //pauses game
                float pauseTime = Time.realtimeSinceStartup + 4f;  //4 seconds
                while (Time.realtimeSinceStartup < pauseTime)
                    yield return 0;
                exitToLevel.gameObject.SetActive(false);
                Time.timeScale = 1;

                SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
           
  }
        }

Item Collected Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;


public class ItemCollected : MonoBehaviour


{


public static int itemcollected=0; //I thought maybe this would reset it to 0, but it didn't
  
void OnTriggerEnter2D(Collider2D other)
    {
        if ((other.CompareTag("Player")))
        {

            Destroy(gameObject); //destroys the item "collects it"
         
itemcollected += 1;  //game keeps track for each one we get on the level so we know when we reach the required amount,   but its being carried over to the next, which is not supposed to
          
        }

That will NOT zero a static object. That’s the entire point of statics: they are associated with the CLASS, not with the INSTANCE that you destroy.

This is why we don’t tend to use static fields except for the very specific few things they are good for.

Tracking items collected is not a good use for static. It’s a lazy use because you’re getting out of passing the instance around, either explicitly or by another pattern such as a game manager.

But if you insist on continuing with static, then when you start your level or your game or whatever, set the value back to zero.

whats another way to track items?

And I tried to set it to zero on the main camera. But didnt work. Whats another way for that?

A game manager pattern is a great way to track such things.

If the game lasts through multiple scenes you can mark the game manager as DontDestroyOnLoad() and it will stick around.

When you’re done with it, destroy it.

The pattern I like is the singleton, and there are tons of examples. This is the simple example I use, and you DO NOT put it in any scene. You just use the class in code via its .Instance property.

Some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data):

https://pastebin.com/SuvBWCpJ

Unity3D Singleton with Prefab used for predefined data:

https://pastebin.com/cv1vtS6G

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

public void DestroyThyself()
{
   Destroy(gameObject);
   Instance = null;    // because destroy doesn't happen until end of frame
}

Thanks.

But when I did try to reset it using your first idea, it was permanently reset. it didn’t register when you collect an item on the next level.

That’s not a thing. It’s just a piece of memory, code can change it. If it’s not changing, then code isn’t changing it.

Yesterday when you posted you had multiple different itemsCollected variables in multiple scripts, some of them static, some of them not. Have you fixed that fundamental flaw first?

Those are all separate pieces of memory, unrelated to each other. Yet if they are named the same, that is a MASSIVE source of confusion. Eliminate it.

You gave me an idea with the game manager thing.

I could try to make a game manager on each level and attach non-static scripts to that for the items, and see if that will work. Because my thinking I wont need that static thing for the whole game, so each game object on each level wont have “public static int itemcollected” but rather “public int itemcollected”. Then the game object that the level is on will read “public int itemcollected” only for the level its on.

its worth a try.

I completely forgot I removed a game object in level 2 and I had a line of code pertaining to that object on the collectable item and I never removed that line.

I made a new script just for level 2 and it didnt work. Once I removed that single line of code it worked.

I cannot believe that potentially I fixed it before but it only didn’t work because of that single line of code…