I have defined a task which generates some files which should go to build directory ($buildDir). Currently I have defined new task for this and trigger it with task dependency:
There is, you can use doFirst { mkdir ... } in your generate task.
Even better, you can write your task as a custom task class and annotate the output directory with @OutputDirectory and it will be created automatically.
Also, I suggest you don’t generate to the build folder directly, but to some subfolder inside there. This will keep the task’s outputs separate from other tasks’s outputs.