0

I have a base class that has a function that does not know what one of the functions it calls will do. That behavior is defined in the child. The parents function is then called from the child. What is the correct syntax/method to make this work? Particularly what must I put instead of FunctionToBeDefinedLater Example follows:

public class ToolScript : MonoBehaviour {
    public void isActive()
    {
        if (Input.GetKeyDown("space"))
        {
            Use();
        }
    }
    FunctionToBeDefinedLater Use();
}

public class GunController : ToolScript
{
    public void Use()
    {
      //Spawn bullet at this direction, this speed, give it spiral, tons of behavior etc. etc.
    }
    private void Update()
    {
      isActive();
    }
}

public class FlamethrowerController : ToolScript
{
    public void Use()
    {
      //Spawn fire at this direction, this speed, set tip of flamethrower to be red etc etc
    }
    private void Update()
    {
      isActive();
    }

}

The Update function is from unity and is called every frame. Please let me know if I can clarify my question any further and I will do so as soon as possible. I do not know if this is referencing overriding, interfacing, or abstraction so I have tagged them all. I will fix this as soon as I know.

Jason Basanese
  • 690
  • 6
  • 20
  • 2
    Read about Abstract and Virtual methods here: https://stackoverflow.com/questions/14728761/difference-between-virtual-and-abstract-methods – Michael Curtiss Oct 06 '17 at 22:12

1 Answers1

0

Based on what @Michael Curtiss directed me to I have updated my code to be:

public **abstract** class ToolScript : MonoBehaviour {
    public void isActive()
    {
        if (Input.GetKeyDown("space"))
        {
            Use();
        }
    }
    **public abstract void** Use();
}

public class GunController : ToolScript
{
    public **override** void Use()
    {
      //Spawn bullet at this direction, this speed, give it spiral, tons of behavior etc. etc.
    }
    private void Update()
    {
      isActive();
    }
}

public class FlamethrowerController : ToolScript
{
    public **override** void Use()
    {
      //Spawn fire at this direction, this speed, set tip of flamethrower to be red etc etc
    }
    private void Update()
    {
      isActive();
    }
}

Stars are not in code and are simply for emphasis. This code solved my problem.

Jason Basanese
  • 690
  • 6
  • 20
  • 2
    You can move the Update() function into the ToolScript class. That way you don't need to type it out for each child class. Call isActive() from there, and it will invoke the relevant Use() function in the child class. – Michael Curtiss Oct 06 '17 at 22:24