How to kill UI on Contact

Hello. So long story short, I need to make a script that kills a timer (UI) when the character touches a edge collider. I’m guessing it has to do with DestroyGameObject or DestroyScriptInstance but I’m still new to scripting. How would I do this? The timer uses DontDestroyOnLoad to go between scenes so that will also have to end. Thank you

You will need a reference to the UI element. When you have it you can just call:

Destroy(myUIElement.gameObject);

The harder part is getting a reference to it. There are many ways to do this. If it’s a DontDestroyOnLoad object, then a singleton pattern may be appropriate. Google “Unity Singleton Pattern” and you will get loads of results on how to do that.

1 Like

You need the reference to said script or gameobject. From there you can either destroy it using Destroy(), or do the better thing and simply reset and disable it.

I’d personally keep the object alive but disable it and reset the timer to a default state. For the latter add a function to your script to stop the timer and set it back to its default values. Then disable the gameobject using SetActive(false). When you need a new timer do the reverse, calling SetActive(true) as well as starting the timer again.
The advantage of this approach is that you wont create garbage (ie loose references which need to be collected by the GC), which prevents spikes in frametimes and thus improves performance. As a rule of thumb, at runtime you never want to destroy objects.

In case the object is unknown to the current scene (common since you use DontDestroyOnLoad) you’ll need to get the reference before doing any of the above. If it’s a one-time deal you can use FindObjectOfType to look for your script in the current scene. However, be aware that all ‘Find’ operations are inherently expensive and thus should be avoided.

Especially if you go with the disabling approach instead of destroying the object, a better approach would be to make the script a singleton. This way you can globally find the reference very cheaply and no matter the scene. You will find plenty when looking for Unity Singleton.

2 Likes

Wow guys. I’ve never even heard of the Unity Singleton Pattern but I found a blog post that describes it pretty well here: http://clearcutgames.net/home/?p=437. Thank you guys!