0
votes

I have a problem i can't seem to fix.

I have an AIManager script. This has all the controls and how my enemy would move. Then I have an EnemyBasic script. This represents the AI behaviour of this enemy. How often he will attack etc.

I tried using a tutorial about Raycasts, that can help me implement sight for my enemies. This worked and my enemy does spot me, tested with a public bool.

Now the problematic part. If I disable the EnemyBasic script my enemy stays in one place, which I want. After I enter his sight I want to activate the EnemyBasic script, so he can start attacking me. Unfortunately, with my code, this gives an error:

NullReferenceException: Object reference not set to an instance of an object Sight.Raycasting () (at Assets/Sight.cs:21) Sight.Update () (at Assets/Sight.cs:13)

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sight : MonoBehaviour {

    public Transform sightStart, sightEnd;
    public bool spotted = false;

    void Update () {
        Raycasting();
    }

     void Raycasting()
    {
        spotted = Physics2D.Linecast(sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Player"));

        if (spotted)
        {
           /*---> LINE OF ERROR */ gameObject.GetComponent<EnemyBasic>().enabled = true;
        }
    }
}

Any ideas. I am new to unity, so there is a high chance its something stupid. Thank you!

1
Double-click on the error and post the line of code that is causing the error. - Programmer
Done. I added an arrow. - TheNewbie
Ok. 1.What is the name of GameObject the Sight script above is attached to? 2.What is the name of GameObject the EnemyBasic script is attached to? - Programmer
Both of them are attached under a GameObject called Enemy1. - TheNewbie
Either gameObject is null or gameObject.GetComponent<EnemyBasic>() is, but there's nothing in the code you've shown that gives us the information to give you a fix. Please post a minimal reproducible example if you want help. - Enigmativity

1 Answers

0
votes

As @Programmer suggested in the comments. Turns out my Sight script was not under the same GameObejct as the EnemyBasic script. Copied the script over and it works like a charm.