- Home /
InvokeRepeating
Hi I'm using c# and I'm currently making a perk script and when the player picks up this perk the players ammo increases every 10 seconds. The perk is a game object as well.However my code doesn't seem to be right as when I play through the game and error comes up saying
Here is the script I have used; public class PerkScript : MonoBehaviour {
public GameObject ammoPerk;
float ammoUpTime = 10f;
// Use this for initialization
void Start () {
InvokeRepeating("TopUpAmmo", ammoUpTime, ammoUpTime);
}
// Update is called once per frame
void Update () {
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
PlayerScript playerScript = GetComponent<PlayerScript>();
if (hit.gameObject.tag == "AmmoPerk")
{
playerScript.reserveAmmo += 10;
Destroy(hit.gameObject);
}
}
}
Thanks for the help if any and would be much appreciated.
Answer by OncaLupe · Dec 13, 2015 at 07:02 PM
So you're trying to invoke a 'TopUpAmmo' method, but you never actually made the method to call. Also, you want this to run after picking up an object, but you're calling it from Start.
You need to move the InvokeRepeating to inside the collision detection code, and make the method itself.
Thanks for the help but is the void OnControllerColliderHit(.....) my method?
Not exactly. There is an error in the logic. You shoud move InvokeRepeating to OnControllerColliderHit, and create new TopUpAmmo public method to increase ammo.
void OnControllerColliderHit(ControllerColliderHit hit)
{
PlayerScript playerScript = GetComponent<PlayerScript>();
if (hit.gameObject.tag == "AmmoPerk")
{
InvokeRepeating("TopUpAmmo", ammoUpTime, ammoUpTime);
Destroy(hit.gameObject);
}
}
public void TopUpAmmo()
{
playerScript.reserveAmmo += 10;
}