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\$
3
  • \$\begingroup\$ Did you write a new Start method in your child class? \$\endgroup\$ Commented Sep 6, 2019 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\$ Commented Sep 6, 2019 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\$ Commented Sep 6, 2019 at 11:28

1 Answer 1

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\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.