0

I had to write a code in the enemy script that when they collides with a bullet damage is taken. Now I want to change this int, (which defines the damage of the bullet) but how? I am getting errors.

enemy script:

public int bulletdamage;

public void dead()
{
    Destroy(gameObject);
}

public void OnCollisionEnter(Collision collision)
{
    if (collision.collider.CompareTag("bullet"))
    {
        Debug.Log("loluhit");
        healthenemy -= bulletdamage;
        if (healthenemy <= 0f)
        {
            dead();
        }
    }
}

It's attached to the enemy, the enemy gets instantiated and gets a random number of live

Then there is the shootscript, where I want to change the int value, to let it be uncluttered:

public int bulletdmg;

void Start()
{
    GetComponent<health>().bulletdamage = bulletdmg;
}

I get the error:

"NullReferenceException: Object reference not set to an instance of an object"

What to do?

3
  • Does this answer your question? Unity C# Null Reference Exception Commented Sep 5, 2020 at 10:40
  • @Lotan that would mean that all enemys loose hp doesn't it? Commented Sep 5, 2020 at 10:42
  • Don't edit "solved" into your question. Instead accept an answer. If necessary create an answer you can accept. Commented Sep 5, 2020 at 13:35

1 Answer 1

1

If you are getting this error on the GetComponentInParent line it's because the parent doesn't have the healt script.

Make sure the object parent have this script attached.

Make sure that health is typed correctly (classes used to start with capital letter).

Sign up to request clarification or add additional context in comments.

5 Comments

but the enemy isn't a child or parent
Then why are you using GetComponentInParent? You should have a reference to the script/object you want, and get that component.
it was a test i used it by accident
and how do i get the reference/how to create it
Let me recommend you this series of video-tutorials made by the people from Unity, will teach you about basic stuff like this: youtube.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.