Weird NullReferenceException

Hey Guys/Gals,
Down here is a script in which I spawn projectiles from a ProjectilePool(Object Pooling). It is attached to a space vehicle, which has a child called ‘Tip’.

void Start ()
	{

		pool = GameObject.FindGameObjectWithTag ("ProjectilePool").GetComponent<ProjectilePool> ();
		if(pool.poolSize <=10)
			pool.poolSize +=10;

		go = pool.RetrieveInstance();
		if(go)
		{
			var script = go.GetComponent<MoveForward>();
			speed = script.speed;								//retrieves common speed of projectiles
		}
		foreach(Transform t in transform)
		{
			if(t.gameObject.name=="Tip")
			{
				tip = t;
				Debug.Log(tip.name);
			}
		}
	}

	public void Update()
	{

	}
	public void Fire ()
	{
		go = pool.RetrieveInstance ();

            Debug.Log(tip);
		var ray=new Ray(tip.position, tip.forward);    \\NullReferenceException
		if (go) 
		{
			go.transform.position = tip.position;
			go.transform.rotation = tip.rotation;

			if(Physics.Raycast(ray, out hit, 100))
			{
				var time = hit.distance / speed;
				StartCoroutine(CastRay(time));
			}
		}
	}

I’ve attached this script to a turret and it works fine, but on this new space car(still finding a name) it gives a NullReferenceException error at the aforementioned line, and Debug.Log(tip); displays Null at runtime. But Debug.Log(tip.name); displays “Tip”. It’s like ‘tip’ is losing it’s value/reference between Start() and Fire(), which is called from another script. What do I do?

I guess, possible reasons are:

  • you could rewrite the tip to null anywhere else in your script; did you post all your script?
  • you could rewrite tip from another script; try to declare tip as {get; private set;} to avoid assigning it from outside (trying do this will cause compiler error);
  • you could call Fire earlier then Start (it could be if object is inactive); check Debug.Log order (Start - first, Fire - after);

less possible are:

  • do you have only one projectile launcher in scene? if more thet one - could it be that you have initiated only first of them, and trying to launch projectile from another? Try to attach name to your Debug.Log in both cases to check this…
  • there could be two scripts attached to one GO by mistake; it’s very silly but I really had such mistake several times :slight_smile:

cant see other reasons yet… try to check them all first…

This might seem dumb guys, but I just had to restart Unity. It works as expected now. Oh, the mysterious ways of the personal computer…