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!
Sightscript above is attached to? 2.What is the name of GameObject theEnemyBasicscript is attached to? - ProgrammergameObjectisnullorgameObject.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