Hello I tried asking this question elsewhere but couldn’t really get an accurate answer so I’m hoping maybe here i can find some more help, I have this code:
public abstract class Test : MonoBehaviour
{
public abstract void OnStart();
public abstract void OnUpdate();
private void Start()
{
OnStart();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.X))
{
Destroy(this);
}
OnUpdate()
}
}
Then I have this :
public class SecondTest : Test
{
public override void OnStart()
{
}
public override void OnUpdate()
{
Writter.Log("Running");
}
}
However whenever I press X, my writter keeps logging, it seems like the instance of “Test” gets destroyed but not my “SecondTest” is there any way to solve this? thank you!
I’m trying to prevent from having Destroy inside SecondTest, because there will be a lot of classes like it and I would like for all of them to be destroyed on keypress, is there no other way of doing this other than adding a check on each sencdtest class?
SecondTest.cs inherits from Test.cs. You cannot destroy an instance of Test.cs and assume it will also destroy SecondTest.cs. You have to destroy the script that you want to destroy. Even another instance of Test.cs will not be destroyed if you only destroyed a certain instance of it.
I’m puzzled as to why this wouldn’t work. Does a debug.log in you base class (outside the if) show up? What about one inside the if?
@hamsterbytedev in the nicest possible way you don’t know what you are talking about. The derived class is the base class. It’s basic polymorphism. Go google it.
I guess I misunderstood the question :-p
You can make a method in the Test.cs class and call that on SecondTest.cs, but for each instance of SecondTest.cs you will have to call that method on it.
So this one was bothering me. As written it should work. @hamsterbytedev and I had some discussion off thread, and both of us think the same thing.
So I actually fired up Unity and put in your scripts as written (+ a semicolon on line 17 of Test :), I also used Debug.Log instead of your Writer.). I attached SecondTest to a GameObject in an empty scene.
And what do you know, this works perfectly as written. Hit play and I get a stream of debugs. Hit X and the component disappears. No more debugs.
So whatever your problem is, its not in the scripts shown here.