I have a c# class that doesn’t extend from MonoBehaviour because it needs to use a constructor. However, this class creates a gameobject in the scene. The problem is I can’t figure out how to get rid of that gameobject from within that MonoBehaviour-less class.
any ideas on how to do this? I’m not all that familiar with C# outside of unity, but googling hasn’t yielded many answers.
Make sure the class uses the appropriate Unity namespace, and then you can call the static Destroy(…) method which, from memory, is in the Object class.
So at the start of the file you need a line something like “using UnityEngine;”, and then when you want to destroy the object you use something like “Object.Destroy(theThingYouWantToDestroy);”.
That’s off the top of my head, forgive any errors! Should get you moving, though.
In order to use Object.Destroy (or most other unity functions) you need to extend your class from Monobehaviour. However, if you extend from MonoBehaviour you can’t create a constructor with your class.
The declaring type of those static methods is UnityEngine.Object.
It’s just that you can invoke them via subclasses of UnityEngine.Object. It’s the same thing in the end, as GameObject.Destroy() is actually Object.Destroy().
A modern IDE such as Visual Studio would also suggest refactoring GameObject.Destroy(…) to Object.Destroy(…) when you’re calling it within a Non-UnityEngine.Object, and refactoring to Destroy(…) when calling from within an Object.
You haven’t paid attention to the thread, right? The static Destroy method is declared in UnityEngine.Object. So yes, ANY class that is derived from that class could be used as well. Using MonoBehaviour.Destroy works but just complicates things and is less clear. As I said, any class could be used. So you could do Material.Destroy, Mesh.Destroy, Transform.Destroy, Camera.Destroy, etc… In any case you will be calling UnityEngine.Object.Destroy.
This meaningless insight really wasn’t worth a necro. It was already mentioned by Suddoha in post #9 5 years ago when someone else already necro’d the post.