- Home /
How to reset a variable?
Hello all, I want to reset my variable int back to "8" after my SphereKILL is instantiated but I cant figure out how. Here's my script:
public GameObject SphereKILL;
public int Counter = 8;
public int FullCounter;
public float timer = 30f;
void Update ()
{
timer -= Time.deltaTime;
{
if (timer <= 0f)
if (Counter >= 0)
Instantiate (SphereKILL, transform.position, transform.rotation);
if (timer <= -1f)
timer = 30f;
if (Counter <= -1)
Time.timeScale = 0;
}
}
public void CountDoody(int howmany)
{
Counter -= howmany;
}
}
Answer by Glurth · Feb 01, 2018 at 07:21 PM
You'll need a value to compare against. You could create another, private reference to the SphereKill object.
private GameObject lastSphereKill;
Inside update, compare your current SphereKill reference with this private one.
if(SphereKill !=lastSphereKill)
{
Counter = 8;
lastSphereKill=SphereKill;
}
Note, this will reset Counter to 8 even if you just delete the reference to SphereKill, setting it to null. Some additional If's could guard against that, if necessary. Edit: Also note, you could do the same thing with an "accessor" to the SphereKill, eliminating the need to store another reference. Alas, accessor's don't play well with Unity's inspector UI and serialization.
Thank you for taking the time to respond. I just tried to incorporate your code inside Update but it didn't work. Let me explain further. I want to Instantiate the Sphere$$anonymous$$ILL every 30 seconds and if there are >= 0 objects inside the Sphere$$anonymous$$ILL then destroy the game objects but if there are <-1 then it's game over. The Sphere$$anonymous$$ILL has a script on it to destroy itself after 2 seconds. The only problem is, the Counter needs to go back to 8 in order for the game to make sense. The counter isn't a life bar, it's only suppose to represent the amount of objects in the Sphere$$anonymous$$ILL. Does that make sense?
I think you may have some other issues with your Update function. for example: when is CountDoody called? I suggest heavy use of Debug.Log()'s. Always useful to see what you are TELLING it to do, vs what you WANT it to to.
So doodycount is called when a certain gameobject collides with the gameobject that has the script I posted on it. I should use Debug.Log() more, yes. Any other suggestions on how to reset that variable?