Coroutines and Item Actions

I have been working on a simple framework for a game of mine and have specifically been working on its item system. I have an IItem interface that all items inherit from and have been working on an abstract Gun class that inherits from IItem and MonoBehaviour. I then have a FirstItem class that inherits from the gun class and calls its base Update method. Here is my code. FrameWork: using UnityEngine;using System.Collections;namespace GearCore{ publ - Pastebin.com and here is the FirstItem class: using UnityEngine;using System.Collections;using GearCore;public class F - Pastebin.com. What I am trying to do is get all my coroutines slowed down to not be called every frame so I don’t have a gun spamming 60 bullets per second and so my gun will only be able to scope in after a certain amount of time after the last call and the same for the ContextUse. I would really appreciate some help on this topic and maybe an idea or two about how to manage the enabled item in an inventory and whatnot.

You keep on starting coroutines inside the coroutines. Worse yet, you are doing it without checking for input. As soon as you have some input, they are all going to trigger at weird times (you are basically starting 60 coroutines a second). Do not do this. It should be more like this:

    //Fire
    public IEnumerator LeftClick()
    {
        while(true) {
            if (Input.GetMouseButton(0))
            {
                Debug.Log("Firing");                    
            }
            yield return new WaitForSeconds(100000);
        }            
    }

This will loop forever, pausing 100000 seconds between calls. It is a single coroutine. You probably want to change that to 1 instead of 100000 though :wink:

I notice a lot of people try treating coroutines as recursive functions, when really they just want an infinite loop that yields control every so often. This is why you use yield really. Sure, you CAN keep firing off couroutines recursively, but I can’t really think of a situation offhand where it makes sense to do that.

EDIT:

To get a little deeper with this; you’ll also want to store your coroutines like this:

Coroutine leftClick = StartCoroutine(LeftClick());

This will allow you to stop them as well (ending the infinite loop) in case you have a need for this. Of course, leftClick should be a member of the class.