- Home /
Problem with Ammo Pickup
Ok, so I have this script on my ammo pickup:
var Ammo : int = 5;
function OnTriggerEnter (theGameObject : Collider)
{
var Gun = GameObject.FindGameObjectsWithTag("spawner");
if(theGameObject.gameObject.tag == "player")
{
Gun.gameObject.GetComponent(RayShoot).GetAmmo(Ammo);
}
Destroy(gameObject);
}
But when i check for errors in the engine, i get this and it doesn't work:
NullReferenceException: Object reference not set to an instance of an object Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.String cacheKeyName, System.Type[] cacheKeyTypes, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory) Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.Object[] args, System.String cacheKeyName, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory) Boo.Lang.Runtime.RuntimeServices.Invoke (System.Object target, System.String name, System.Object[] args) Ammo Boost1.OnTriggerEnter (UnityEngine.Collider theGameObject) (at Assets/scripts/Powerups/Ammo Boost1.js:9)
I don't understand what the issue is and t can't be the script that is attached to my gun because i used this code previously:
var Ammo : int = 5;
var Gun : GameObject;
function OnTriggerEnter (theGameObject : Collider)
{
if(theGameObject.gameObject.tag == "player")
{
Gun.gameObject.GetComponent(RayShoot).GetAmmo(Ammo);
}
Destroy(gameObject);
}
and it works perfectly, and yes all the tags are in order properly. Could it be because of the fact that the Gun object that the first script is trying to access is under multiple parents?
Answer by aldonaletto · Sep 07, 2011 at 02:19 AM
In the second script, Gun is the reference to an object you've specified. In the first one, Gun is an array containing all "spawner" objects. You should use it as Gun[0] to get the first "spawner" object. Probably the compiler created a new temporary Gun variable and used it with GetComponent, what caused the error.
You should use FindWithTag instead:
var Gun = GameObject.FindWithTag("spawner");and preferably inside Start - but with Gun declared outside the function, like this:
var Gun: GameObject;
function Start(){ Gun = GameObject.FindWithTag("spawner"); }
function OnTriggerEnter( if(theGameObject.gameObject.tag == "player") { Gun.gameObject.GetComponent(RayShoot).GetAmmo(Ammo); } Destroy(gameObject); }
Great! It works perfectly. Thanks, but what if i want to instantiate the player prefab? Then when i start the scene the variable gun has nothing assigned to it and for some reason when the player is instantiated there is still nothing assigned.
Sorry, never$$anonymous$$d, all i had to do was put the findwithtags in the update function.
You should not place it at Update because all Find functions are slow and may affect your frame rate. But you can move this instruction to OnTriggerEnter like before, since it will be called very seldomly.