Bob T. Bob T. - 1 year ago 94
C# Question

Show dialog only once, not after level restart

I have my own dialog system which is basically a gameobject with a collider. After triggering collider,

with a
component should show up. So far, this works. Now, I want to make it happen only once. Here how its work: I start level trigger showing dialog. Game is pretty hardcore so player probably will die. When player dies, I call
(so basically I restart level)

If I use something like this in scrip with collider

private static bool firstTimeText = true;

void OnTriggerEnter2D(Collider2D coll)
if (coll.tag == "Player" && firstTimeText)
GetComponent<BoxCollider2D>().enabled = false;
firstTimeText = false;

everything works like a charm. EXCEPT if I make copy of this gameobject, static variable in script will "handle" that every instantion of this object will have firstTimeText on false after trigger dialog first time. So basically I can use it only once.

So is there any sollution for making trigger which run only once and not reset after

Also this doesn't work

void Awake()

Answer Source

Static variables are globally identical - therefore if you need to have multiple gameobjects exhibiting this behavior, they'll need to hook into different static values in some way.

One way to do this would be to have a key, and then keeping a static list of all "keys" already displayed. My recommendation would be a HashSet - thus

private static HashSet<string> firstTimeSet = new HashSet<string>();

public string singleRunKey;

void OnTriggerEnter2D(Collider2D coll)
    if (coll.tag == "Player"
        && firstTimeSet.Add(singleRunKey))
    { GetComponent<BoxCollider2D>().enabled = false; }

Note that .Add returns true if the item wasn't in the collection (and adds it), but false if it already was (and does not add it, because no duplicates). All you have to do now is assign singleRunKey a unique value per object via the Inspector, and each one will run exactly once

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download