So my project was running fine last night, and now today I have a null reference. I haven’t changed anything about my project since last night and I can’t find why there is an error.
Here is the code I have:
public WeaponType weapon;
GameObject player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
public void SelectWeapon()
{
DeselectAll();
GetComponent<Image>().color = Color.grey;
player.GetComponent<PController>().weaponType = weapon; //this is the line that is throwing the error
}
On the PController script I have:
public enum WeaponType
{
Bullet,
Missile,
Grenade
}
public class PController : MonoBehaviour
{
public WeaponType weaponType;
private IWeapon iWeapon;
}
That’s the only code that would have anything to do with the error. I can’t figure out why there would be an error though, it doesn’t make any sense.
I seem to have narrowed down the problem. In my player script I have a line in the start function that selects the weapon. But the script appears to be called before the player loads (or at least that’s the best explanation I can come up with)
I tried moving the code to the Awake() function but that didn’t change anything. Anyone know what is going on?
Well clearly it is failing to find a GO in the scene with the proper tag. Double check you are loading the right scene BEFORE this object is activated?
Regardless though, this code is very fragile. You should ALWAYS verify your return results and always be prepared for unexpected returns. Instead of just assuming that you have a valid GO you should verify it before using it. Same thing with how you set the color. What if there wasn’t an Image component found? Your code would crash.
I doubled checked all the tags and everything. Nothing changed. The weird part is that when I turned everythinf off last night it was working fine but now this morning it doesn’t work. It seems like nothing should have changed.
I’ll try adding in some verifying. Should I just put them in simple if statements?
Like
if (player)
{
Do the thing
}
Or should I use something a little more robust?
I added a Debug.Log(player) in the Start () function just after finding the Player Gameobject. (The code from the first batch of code) and it finds the player just fine. No errors at all. So why isn’t it finding the component attached to the player when I call the code later in the code?
you can change start into coroutine and wait until player gameobject is created…