using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class testscript : MonoBehaviour
{
// Start is called before the first frame update
private CharacterMaster characterMaster;
public GameObject test;
void Start()
{
characterMaster = FindObjectOfType<CharacterMaster>();
Debug.Log(characterMaster);
characterMaster.addCharacterObj(test);
foreach (Transform child in test.transform){
characterMaster.addCharacterObj(child.gameObject);
}
}
}
i have this short script ot test something else but for some reason it creates a NullReferenceException.
the debug statement tells me that it has the correct instance of the CharacterMaster but for some reason it then proceeds to give the exception. this is what the console tells me:
GlobalManager (CharacterMaster)
UnityEngine.Debug:Log (object)
testscript:Start () (at Assets/Scripts/testscript.cs:13)
NullReferenceException: Object reference not set to an instance of an object
testscript.Start () (at Assets/Scripts/testscript.cs:14)
You don’t need a forum post, debug every reference on that line, something is NULL. That’s the end of it really!
It’s by far the most common problem posted on these forums each and every day. We have a pinned post about it here .
if(characterMaster!=null||test!=null){
characterMaster.addCharacterObj(test);
}
for some reason this still executes so i am not sure what could be null in this line
I think you should use && rather than || for your null check. The way you have it, it will only work if both references are null.
Either CharacterMaster is null or test is null. You should debug log both of them prior to calling characterMaster.AddCharacterObj
okay i have it reduced it to this:
test = gameObject;
if(test != null){
Debug.Log("ha");
characters.Add(test);
}
and i still get a null reference exception (characters is a list of gameobjects)
it seems as if unity magically changes test to null between lines
In that snippet you don’t do a null check on characters, so it could be that causing the exception rather than test.
As MelvMay says, something is null, you need to check for every possible null reference on the line that is throwing the exception.
Try attaching a debugger and putting in a breakpoint on that line. That way you can quickly inspect what everything is. This is an essential tool if you every want to be writing games and any complexity.
Code Debugging
You probably just have this script on another GameObject as well and you haven’t realized it yet.