Hello everyone, I’m having a weird issue been looking around for a solution and nothing so far, so I’d like to know why am I getting this error?
Here’s the script attached, how to fix it so I don’t get this error?
public Transform monsterTransform;
private MonsterEnemy monster;
void Start ()
{
monster = FindObjectOfType<MonsterEnemy>();
}
void Update ()
{
if (monster.enabled == true)
{
Destroy(GameObject.FindGameObjectWithTag("Enemy"));
}
if (monster.enabled == false)
return;
}
void FixedUpdate ()
{
monsterTransform = GameObject.FindGameObjectWithTag("Monster").transform;
if (monster.enabled == true)
Destroy(GameObject.FindGameObjectWithTag("Enemy"));
if (monster.enabled == false)
return;
}
}
Thanks in advance.
Because some object reference is not set to an instance of an object. Since you’re not posting the entire error message, I can’t know which, but it’s either that monsterTransform is not set in the inspector, FindObjectOfType() does not find a MonsterEnemy in the scene, or possibly GameObject.FindGameObjectWithTag(“Enemy”) doesn’t find an object with the Enemy tag.
Here’s the error message all of it.
NullReferenceException: Object reference not set to an instance of an object
DestroyOthersIfMonsterIsOn.Update () (at Assets/MyGameScripts/DestroyOthersIfMonsterIsOn.cs:18)
So on line 18 of DestroyOthersIfMonsterIsOn.cs you should expect to find an object that is not necessarily holding a reference to an object instance.
Maybe you expect that object at that line of code to later hold a reference? Or perhaps its de-referenced at runtime because something else in code destroyed it already? Both common situations…
Ok, so line 18 in your code isn’t line 18 in what you pasted, so I’m still a bit unsure, but I’m going to guess it’s the line if(monster.enabled==true) If this is the case, the following method returns null because it couldn’t find a MonsterEnemy in the scene: monster = FindObjectOfType<MonsterEnemy>(); Remember that when you call this in Start, they have to be in the scene when the level starts. To confirm if this is the case you can try to do something like this
void Start() {
monster = FindObjectOfType<MonsterEnemy>();
if (monster == null) { Debug.Log("Monster not found"); }
}
This will print a message in the log if a MonsterEnemy isn’t found at start.
Still same issue, didn’t fix it, I did all you mentioned, how can I do it is there a way around that when this monster appears every other enemy tagged object be destroyed? he has a timer he appears every 6 mins.
Solved, I had the script also attached to something else another game object and it was causing that issue, thanks a lot for the suggestions!