Search Unity

Trying to figure out how to execute code at build

Discussion in 'Scripting' started by Tarnarmour, Aug 1, 2019.

  1. Tarnarmour

    Tarnarmour

    Joined:
    Jul 17, 2019
    Posts:
    4
    So to preface I'm pretty new at Unity, I'm trying to get some code working for a test my lab is doing soon. I need to be doing some file IO stuff and I want to create a directory for all the input/output files to be put into. I can create that directory at run time if it isn't there yet but obviously it won't be there until the game is run the first time. I want to create this directory when the game is built. I have the following code that should create the directory correctly, it just doesn't seem to be run. I'm not sure where to put it or if there's anything else I need to add to it to let unity know I want it run on build.

    #if UNITY_EDITOR
    using UnityEditor;
    using UnityEditor.Build;
    using UnityEngine;
    using System;
    using System.IO;

    class MyCustomBuildProcessor : IPreprocessBuild
    {
    public int callbackOrder { get { return 0; } }
    public void OnPreprocessBuild(BuildTarget target, string path)
    {
    // Do the preprocessing here
    string directoryPath = Application.dataPath + "/ITSWORKING";
    Directory.CreateDirectory(directoryPath);
    }
    }
    #endif
     
  2. https://docs.unity3d.com/ScriptReference/Application-dataPath.html

    You want to use the persistentDataPath instead.
    https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html
     
  3. Tarnarmour

    Tarnarmour

    Joined:
    Jul 17, 2019
    Posts:
    4
    I replaced dataPath with persistentDataPath but it does not fix the issue. I don't think the dataPath is the problem because I actually have some other Monobehaviour scripts that are called at game start that use dataPath to create some folders and files and those all work just fine.

    I think that this script, which I just have stored in the assets file, is not getting called when the game is built and I don't know how to get it run at build time.
     
  4. Tarnarmour

    Tarnarmour

    Joined:
    Jul 17, 2019
    Posts:
    4
    Okay I think I found the problem, it was a misunderstanding on my part. I thought that the build function would be called as the game was built and the file generated would be stored in the dataPath for the build, not the project. The function I have here creates a directory in the project/assets directory. I still don't know how to create the directory in the same location as the build is located.
     
  5. Ah OK, I misunderstood as well.

    Try this: https://docs.unity3d.com/ScriptReference/Callbacks.PostProcessBuildAttribute.html