0
\$\begingroup\$

I have Block class which is the parent and StandardBlock the child , the prefab block have StandardBlock script attached to it, and according to my small knowledge in inheriting I though this would work

public class Block : MonoBehaviour
{
HUD HUDscript;
// Start is called before the first frame update
void Start()
{
    HUDscript = GameObject.FindWithTag("Canvas").GetComponent<HUD>();  
}
public void OnCollisionEnter2D(Collision2D col)
{
    HUDscript.addPoints();
    Destroy(gameObject);
}
}

and child class

public class StandardBlock : Block
 {

      // some code
}

but this is the error that i got

NullReferenceException: Object reference not set to an instance of an object Block.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets/Scripts/Gameplay/Block.cs:24)

while writing OnCollisionEnter2D in the child class worked fine

\$\endgroup\$
  • \$\begingroup\$ Did you write a new Start method in your child class? \$\endgroup\$ – DMGregory Sep 6 at 1:13
  • \$\begingroup\$ @DMGregory yes I did , so now I can see the problem, I didn't write base.start() in child start method, now it's working fine. Thank you a lot \$\endgroup\$ – Abeer Sep 6 at 11:26
  • \$\begingroup\$ If you've solved your problem, please write up your solution as an Answer. :) You'll be able to mark it as Accepted after a short delay, and other users can up-vote it if they find it helpful. \$\endgroup\$ – DMGregory Sep 6 at 11:28
1
\$\begingroup\$

Since I used a start method too in the child class I should have written it that way

override protected void Start()
{
    //some code
    base.Start();
}

and in the parent class

virtual protected void Start()
{
    HUDscript = GameObject.FindWithTag("Canvas").GetComponent<HUD>();


}

so now the child can implement both methods

Thanks to @DMGregory

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.