- Home /
GetComponent not Returning
Hello guys, i make a Pickup script of ammo, 1 script in AmmoBox with information of quantity of ammo and when i put mouse over the ammo box show on gui the ammo of the ammoBox, i I used Raycast, "Hit.collider.gameObject" Here the code with only the GetComponent:
var otherObject = Hit.collider.gameObject;
municaoAtual = otherObject.GetComponent("AmmoBox").bulletsAmount;
But, the GetComponent is not returning :/ show only "0" and in log not show any erros. Sorry for my english xD and Happy New Year!
Answer by rabbitfang · Jan 01, 2012 at 08:23 PM
You need to cast the returned component (from GetComponent()
) to your script type (in this case, AmmoBox
). To do so, change that line to
municaoAtual = (otherObject.GetComponent("AmmoBox") as AmmoBox).bulletsAmount;
Also, it is probably better to use an actual type rather than a string when using GetComponent
because 1) it is likely faster 2) it will be easier to debug if you ever change the name of AmmoBox
.
Not Work, i not know but GetComponent never work here, have other way? Note: the "otherObject" is from a RayCast, That may change at any time the object.
I use for example, var script : AmmoBox and later, script.variable, but the Object may change at any time :/
LOL, when i When I was testing I noticed that for example, appears in the GUI of the amount of ammunition that was Last equipped ammobox!