Unity Add Default Namespace to Script Template? - c#

I just found Unity's script template for C# scripts. To get the script name you write #SCRIPTNAME# so it looks like this:
using UnityEngine;
using System.Collections;
public class #SCRIPTNAME# : MonoBehaviour
{
void Start ()
{
}
void Update ()
{
}
}
Then it would create the script with the right name, but is there something like #FOLDERNAME# so that I can put it in the right namespace directly when creating the script?

There is no built-in template variables like #FOLDERNAME#.
According to this post, there are only 3 magic variables.
"#NAME#"
"#SCRIPTNAME#"
"#SCRIPTNAME_LOWER#"
But you can always hook into the creation process of a script and append the namespace yourself using AssetModificationProcessor.
Here is an example that adds some custom data to the created script.
//Assets/Editor/KeywordReplace.cs
using UnityEngine;
using UnityEditor;
using System.Collections;
public class KeywordReplace : UnityEditor.AssetModificationProcessor
{
public static void OnWillCreateAsset ( string path )
{
path = path.Replace( ".meta", "" );
int index = path.LastIndexOf( "." );
string file = path.Substring( index );
if ( file != ".cs" && file != ".js" && file != ".boo" ) return;
index = Application.dataPath.LastIndexOf( "Assets" );
path = Application.dataPath.Substring( 0, index ) + path;
file = System.IO.File.ReadAllText( path );
file = file.Replace( "#CREATIONDATE#", System.DateTime.Now + "" );
file = file.Replace( "#PROJECTNAME#", PlayerSettings.productName );
file = file.Replace( "#SMARTDEVELOPERS#", PlayerSettings.companyName );
System.IO.File.WriteAllText( path, file );
AssetDatabase.Refresh();
}
}

I know it's and old question but in newer versions of Unity you can define a root namespace to be used in the project.
You can define the namespace in Edit > Project Settings > Editor > Root Namespace
Doing this will add the defined namespace on newly created scripts.

Using zwcloud's answer and some other resources I was able to generate a namespace on my script files:
First step, navigate:
Unity's default templates can be found under your Unity installation's directory in Editor\Data\Resources\ScriptTemplates for Windows and /Contents/Resources/ScriptTemplates for OSX.
And open the file 81-C# Script-NewBehaviourScript.cs.txt
And make the following change:
namespace #NAMESPACE# {
At the top and
}
At the bottom. Indent the rest so that the whitespace is as desired. Don't save this just yet. If you wish, you can make other changes to the template, such as removing the default comments, making Update() and Start() private, or even removing them entirely.
Again, do not save this file yet or Unity will throw an error on the next step. If you saved, just hit ctrl-Z to undo and then resave, then ctrl-Y to re-apply the changes.
Now create a new script inside an Editor folder inside your Unity Assets directory and call it AddNameSpace. Replace the contents with this:
using UnityEngine;
using UnityEditor;
public class AddNameSpace : UnityEditor.AssetModificationProcessor {
public static void OnWillCreateAsset(string path) {
path = path.Replace(".meta", "");
int index = path.LastIndexOf(".");
if(index < 0) return;
string file = path.Substring(index);
if(file != ".cs" && file != ".js" && file != ".boo") return;
index = Application.dataPath.LastIndexOf("Assets");
path = Application.dataPath.Substring(0, index) + path;
file = System.IO.File.ReadAllText(path);
string lastPart = path.Substring(path.IndexOf("Assets"));
string _namespace = lastPart.Substring(0, lastPart.LastIndexOf('/'));
_namespace = _namespace.Replace('/', '.');
file = file.Replace("#NAMESPACE#", _namespace);
System.IO.File.WriteAllText(path, file);
AssetDatabase.Refresh();
}
}
Save this script as well as saving the changes to 81-C# Script-NewBehaviourScript.cs.txt
And you're done! You can test it by creating a new C# script inside any series of folders inside Assets and it will generate the new namespace definition we created.

I'm well aware that this question has been answered by the awesome people (zwcloud, Darco18 and Alexey).
However, since my namespace organization follows the folder structure in the project, I've put together in a jiffy some minor modification to the code, and I'm sharing it here in case someone needs it and has the same organizational methodology which I'm following.
Please keep in mind that you need to set the root namespace in your project settings in the C# project generation section.
EDIT: I've adjusted the code a bit work with placement in the root folders of Scripts, Editor, etc..
public class NamespaceResolver : UnityEditor.AssetModificationProcessor
{
public static void OnWillCreateAsset(string metaFilePath)
{
var fileName = Path.GetFileNameWithoutExtension(metaFilePath);
if (!fileName.EndsWith(".cs"))
return;
var actualFile = $"{Path.GetDirectoryName(metaFilePath)}\\{fileName}";
var segmentedPath = $"{Path.GetDirectoryName(metaFilePath)}".Split(new[] { '\\' }, StringSplitOptions.None);
var generatedNamespace = "";
var finalNamespace = "";
// In case of placing the class at the root of a folder such as (Editor, Scripts, etc...)
if (segmentedPath.Length <= 2)
finalNamespace = EditorSettings.projectGenerationRootNamespace;
else
{
// Skipping the Assets folder and a single subfolder (i.e. Scripts, Editor, Plugins, etc...)
for (var i = 2; i < segmentedPath.Length; i++)
{
generatedNamespace +=
i == segmentedPath.Length - 1
? segmentedPath[i]
: segmentedPath[i] + "."; // Don't add '.' at the end of the namespace
}
finalNamespace = EditorSettings.projectGenerationRootNamespace + "." + generatedNamespace;
}
var content = File.ReadAllText(actualFile);
var newContent = content.Replace("#NAMESPACE#", finalNamespace);
if (content != newContent)
{
File.WriteAllText(actualFile, newContent);
AssetDatabase.Refresh();
}
}
}

OK, so this question was already answered by two wonderful people, zwcloud and Draco18s, and their solution works, I'm just showing another version of the same code that, I hope, will be a little more clear in terms of what exactly happening.
Quick notes:
Yes, in this method we are getting not the actual file path,
but the path of its meta file as a parameter
No, you can not use AssetModificationProcessor without UnityEditor prefix, it is deprecated
OnWillCreateAsset method is not shown via Ctrl+Shift+M, 'override' typing or base class metadata
_
using UnityEditor;
using System.IO;
public class ScriptTemplateKeywordReplacer : UnityEditor.AssetModificationProcessor
{
//If there would be more than one keyword to replace, add a Dictionary
public static void OnWillCreateAsset(string metaFilePath)
{
string fileName = Path.GetFileNameWithoutExtension(metaFilePath);
if (!fileName.EndsWith(".cs"))
return;
string actualFilePath = $"{Path.GetDirectoryName(metaFilePath)}{Path.DirectorySeparatorChar}{fileName}";
string content = File.ReadAllText(actualFilePath);
string newcontent = content.Replace("#PROJECTNAME#", PlayerSettings.productName);
if (content != newcontent)
{
File.WriteAllText(actualFilePath, newcontent);
AssetDatabase.Refresh();
}
}
}
And this is the contents of my file c:\Program Files\Unity\Editor\Data\Resources\ScriptTemplates\81-C# Script-NewBehaviourScript.cs.txt
using UnityEngine;
namespace #PROJECTNAME#
{
public class #SCRIPTNAME# : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
}

Here is my solution, in my case Unity added the root namespace right before OnWillCreateAsset(), so I had to replace the root namespace in the script with the one I want.
Here is the code
public class AddNameSpace : UnityEditor.AssetModificationProcessor
{
public static void OnWillCreateAsset(string path)
{
var rootNamespace =
string.IsNullOrWhiteSpace(EditorSettings.projectGenerationRootNamespace) ?
string.Empty : $"{EditorSettings.projectGenerationRootNamespace}";
path = path.Replace(".meta", "");
int index = path.LastIndexOf(".");
if (index < 0)
return;
string file = path.Substring(index);
if (file != ".cs" && file != ".js" && file != ".boo")
return;
string formattedNamespace = GetNamespace(path, rootNamespace);
file = System.IO.File.ReadAllText(path);
if (file.Contains(formattedNamespace))
return;
file = file.Replace(rootNamespace, formattedNamespace);
System.IO.File.WriteAllText(path, file);
AssetDatabase.Refresh();
}
private static string GetNamespace(string filePath, string rootNamespace)
{
filePath = filePath.Replace("Assets/Scripts/", "/")
.Replace('/', '.')
.Replace(' '.ToString(), string.Empty);
var splitPath = filePath.Split('.');
string pathWithoutFileName = string.Empty;
for (int i = 1; i < splitPath.Length - 2; i++)
{
if (i == splitPath.Length - 3)
{
pathWithoutFileName += splitPath[i];
}
else
{
pathWithoutFileName += splitPath[i] + '.';
}
}
return $"{rootNamespace}.{pathWithoutFileName}";
}
}

Related

Unity WebGL Simple JSON

I am trying to import text in my Unity script with WebGL but it seems like in WebGL, it is not able to find the JSON file itself. I have saved the file in StreamingAssets. How do I fix this?
using System.Collections;
using System.Collections.Generic;
using System.IO;
using SimpleJSON;
using UnityEngine;
using UnityEngine.UI;
public class ReadScene : MonoBehaviour {
public string jsonFile;
JSONNode itemsData;
string path;
public Text sceneText;
// Start is called before the first frame update
void Start () {
path = Path.Combine (Application.streamingAssetsPath, "Settings.json");
if (File.Exists (path)) {
jsonFile = File.ReadAllText (path);
DeserializePages ();
} else {
sceneText.gameObject.SetActive(false);
}
}
public void DeserializePages () {
itemsData = JSON.Parse (jsonFile);
var parseJSON = JSON.Parse (jsonFile);
sceneText.text = parseJSON["Scene01"].Value;
}
}
Also I have tried to change the folder location to "Resources" and still facing the same issue.
From Application.streamingAssetsPath
It is not possible to access the StreamingAssets folder on WebGL and Android platforms. No file access is available on WebGL. Android uses a compressed .apk file. These platforms return a URL. Use the UnityWebRequest class to access the Assets.
tbh I don't even know right now whether this No file access is available on WebGL is just misleading or indeed means there is no way to access StreamingAssets. I will assume it is just formulated badly and just means you can not access any file/directory directly but you can still go through UnityWebRequest.Get like
IEnumerator Start ()
{
sceneText.gameObject.SetActive(false);
path = Path.Combine(Application.streamingAssetsPath, "Settings.json");
using(var request = UnityWebRequest.Get(path))
{
yield return request.SendWebRequest();
if(!request.result == UnityWebRequest.Result.Success)
{
Debug.LogError("Error: " + result.error);
yield break;
}
jsonFile = webRequest.downloadHandler.text;
DeserializePages();
}
}
private void DeserializePages()
{
itemsData = JSON.Parse (jsonFile);
sceneText.text = itemsData["Scene01"].Value;
sceneText.gameObject.SetActive(true);
}

File.WriteAllLines not working in C# (Visual Studio 19)

I am making a program in c#. I am trying to access a file (named counter.txt, in the Logs folder) using C#'s File class. I am reading the file, storing the only line in a variable named count, I increase it by 1, and then I write it back into the file. The reading and incrementation work, but the writing doesn't. I've tried to use different datatypes for the output container (string[], List<string>, ...). Nothing works. I am following a tutorial, and the code works fine there. I suppose it is a Visual Studio 19 or an antivirus/permission issue? Here is the code, any help would be greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
namespace Program
{
class Logger
{
private int count = 0;
// setup
public void Start()
{
string counterFile = #".\\Logs\\counter.txt";
string line = File.ReadAllLines(counterFile)[0];
count = int.Parse(line);
count++;
string[] toWrite = {count.ToString()};
Console.WriteLine(counterFile);
File.WriteAllLines(counterFile, toWrite);
Console.WriteLine(count);
}
}
}
The file structure (Logger.cs is the file I'm doing this in):
As identified in the comments, the problem is that you've added counter.txt to Visual Studio, with a "Copy to output directory" property of "Always".
This means that whenever you build your project, Visual Studio will copy that counter.txt to your bin directory, overwriting whatever file was there before.
Your application is, of course, modifying the copy in the bin directory.
A better approach would be to remove counter.txt from your file list in Visual Studio entirely, and instead all logic to your problem to create the file if it doesn't already exist. Something like:
class Logger
{
private int count = 0;
// setup
public void Start()
{
string counterDirectory = "Logs";
string counterFile = Path.Join(counterDirectory, "counter.txt");
if (!Directory.Exists(counterDirectory))
{
Directory.CreateDirectory(counterDirectory);
}
if (File.Exists(counterFile))
{
string line = File.ReadAllLines(counterFile)[0];
count = int.Parse(line);
count++;
}
else
{
count = 1;
}
string[] toWrite = {count.ToString()};
Console.WriteLine(counterFile);
File.WriteAllLines(counterFile, toWrite);
Console.WriteLine(count);
}
}
Another problem you are going to run into at some point is that the path to your file is relative, and therefore relative to the user's current working directory.
This might be the directory containing your application, but it might not be: try opening a command prompt inside your bin folder and then running Debug\YourApplication.exe, and see that Logs is created in your current directory!
Instead, you probably want to do something like:
class Logger
{
private int count = 0;
// setup
public void Start()
{
string applicationDirectory = Path.GetDirectoryName(typeof(Logger).Assembly.Location);
string counterDirectory = Path.Join(applicationDirectory , "Logs");
string counterFile = Path.Join(counterDirectory, "counter.txt");
if (!Directory.Exists(counterDirectory))
{
Directory.CreateDirectory(counterDirectory);
}
if (File.Exists(counterFile))
{
string line = File.ReadAllLines(counterFile)[0];
count = int.Parse(line);
count++;
}
else
{
count = 1;
}
string[] toWrite = {count.ToString()};
Console.WriteLine(counterFile);
File.WriteAllLines(counterFile, toWrite);
Console.WriteLine(count);
}
}
Also your code to read/write the file is overly complex: there's no need to use arrays here, as the file only contains a single line! You can get away with something like:
class Logger
{
private int count = 0;
// setup
public void Start()
{
string applicationDirectory = Path.GetDirectoryName(typeof(Logger).Assembly.Location);
string counterDirectory = Path.Join(applicationDirectory , "Logs");
string counterFile = Path.Join(counterDirectory, "counter.txt");
if (!Directory.Exists(counterDirectory))
{
Directory.CreateDirectory(counterDirectory);
}
if (File.Exists(counterFile))
{
string contents = File.ReadAllText(counterFile);
count = int.Parse(contents);
count++;
}
else
{
count = 1;
}
Console.WriteLine(counterFile);
File.WriteAllText(counterFile, count.ToString());
Console.WriteLine(count);
}
}
Your code works just fine if the path to the file is correct and your app is able to access that folder, the file is not locked, etc.
I was trying this code:
using System;
using System.IO;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int count;
string counterFile = #"D:\tmp\counter.txt";
string line = File.ReadAllLines(counterFile)[0];
count = int.Parse(line);
count++;
string[] toWrite = { count.ToString() };
Console.WriteLine(counterFile);
File.WriteAllLines(counterFile, toWrite);
Console.WriteLine(count);
}
}
}
With the file containing 5. Here is the result:
The updated file looks like:
Update. You have to check that your file is copied on build. That's might be your issue

How do I get a branches parent from a path in TFS

Lets say the following is my TFS structure:
Branches (Folder)
Module1 (Folder)
Branch1 (Branch with parent Dev)
Branch2 (Branch with parent Branch1)
Branch3 (Branch with parent Branch1)
Dev (Branch)
In code, I have access to my local workspace, as well as a VersionControlServer object.
I want a method such as string GetParentPath(string path)
that would act like the following:
GetParentPath("$/Branches/Module1/Branch1"); // $/Dev
GetParentPath("$/Branches/Module1/Branch2"); // $/Branches/Module1/Branch1
GetParentPath("$/Branches/Module1/Branch3"); // $/Branches/Module1/Branch1
GetParentPath("$/Dev"); // throws an exception since there is no parent
I currently have the following, thought it worked, but it doesn't (and I didn't honestly expect it to work either)
private string GetParentPath(string path)
{
return versionControlServer.QueryMergeRelationships(path)?.LastOrDefault()?.Item;
}
You can get all branch hierarchies (Parent/Child) using below code: (Install the Nuget package Microsoft.TeamFoundationServer.ExtendedClient)
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace DisplayAllBranches
{
class Program
{
static void Main(string[] args)
{
string serverName = #"http://ictfs2015:8080/tfs/DefaultCollection";
//1.Construct the server object
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(serverName));
VersionControlServer vcs = tfs.GetService<VersionControlServer>();
//2.Query all root branches
BranchObject[] bos = vcs.QueryRootBranchObjects(RecursionType.OneLevel);
//3.Display all the root branches
Array.ForEach(bos, (bo) => DisplayAllBranches(bo, vcs));
Console.ReadKey();
}
private static void DisplayAllBranches(BranchObject bo, VersionControlServer vcs)
{
//0.Prepare display indentation
for (int tabcounter = 0; tabcounter < recursionlevel; tabcounter++)
Console.Write("\t");
//1.Display the current branch
Console.WriteLine(string.Format("{0}", bo.Properties.RootItem.Item));
//2.Query all child branches (one level deep)
BranchObject[] childBos = vcs.QueryBranchObjects(bo.Properties.RootItem, RecursionType.OneLevel);
//3.Display all children recursively
recursionlevel++;
foreach (BranchObject child in childBos)
{
if (child.Properties.RootItem.Item == bo.Properties.RootItem.Item)
continue;
DisplayAllBranches(child, vcs);
}
recursionlevel--;
}
private static int recursionlevel = 0;
}
}
Figured it out (Thanks to Andy Li-MSFT for poking my brain with the BranchObject class):
string GetParentPath(string path)
{
BranchObject branchObject = versionControlServer.QueryBranchObjects(new ItemIdentifier(path), RecursionType.None).Single();
if (branchObject.Properties.ParentBranch != null)
return branchObject.Properties.ParentBranch.Item;
else
throw new Exception($"Branch '{path}' does not have a parent");
}
In addition, if you want to get the parent branch of a file/folder located within that branch, you could use the following code to get that functionality:
private string GetParentPath(string path)
{
string modifyingPath = path;
BranchObject branchObject = versionControlServer.QueryBranchObjects(new ItemIdentifier(modifyingPath), RecursionType.None).FirstOrDefault();
while (branchObject == null && !string.IsNullOrWhiteSpace(modifyingPath))
{
modifyingPath = modifyingPath.Substring(0, modifyingPath.LastIndexOf("/"));
branchObject = versionControlServer.QueryBranchObjects(new ItemIdentifier(modifyingPath), RecursionType.None).FirstOrDefault();
}
string root = branchObject?.Properties?.ParentBranch?.Item;
return root == null ? null : $"{root}{path.Replace(modifyingPath, "")}";
}

Unity Cloud Build: post export method

Problem:
I can't seem to figure out the right signature for Unity cloud build's post export method. According to the documentation:
The fully-qualified name of a public static method you want us to call
after we finish the Unity build process (but before Xcode). For
example: ClassName.CoolMethod or NameSpace.ClassName.CoolMethod. No
trailing parenthesis, and it can't have the same name as your
Pre-Export method! This method must accept a string parameter, which
will receive the path to the exported Unity player (or Xcode project
in the case of iOS).
Here is my code:
public static void OnPostprocessDevBuildIOS(string ExportPath)
{
var projPath = ExportPath + "/Unity-iPhone.xcodeproj/project.pbxproj";
var proj = new PBXProject();
var nativeTarget =
proj.TargetGuidByName(PBXProject.GetUnityTargetName());
var testTarget =
proj.TargetGuidByName(PBXProject.GetUnityTestTargetName());
string[] buildTargets = {nativeTarget, testTarget};
proj.ReadFromString(File.ReadAllText(projPath));
proj.SetBuildProperty(buildTargets, "ENABLE_BITCODE", "NO");
File.WriteAllText(projPath, proj.WriteToString());
}
and here is the error:
I've tried multiple test method signatures and can't seem to get anything to work. I've even tried just a method that logs out the path.
Additional Information:
Unity Version: 5.3.1f
Unity Cloud Build: 5.3.1f
Target: iOS 8.0+
Also, my cloud build settings script is located in the editor folder as required.
Ok so I got the the bitCode disabling post process to work with the following code, but only when I build manually. When I build from cloud build, with no error the app freezes at the splash screen. When I build from my local machine, the app runs just fine.
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
{
if (buildTarget == BuildTarget.iOS)
{
string projPath = path + "/Unity-iPhone.xcodeproj/project.pbxproj";
PBXProject proj = new PBXProject();
proj.ReadFromString(File.ReadAllText(projPath));
string nativeTarget = proj.TargetGuidByName(PBXProject.GetUnityTargetName());
string testTarget = proj.TargetGuidByName(PBXProject.GetUnityTestTargetName());
string[] buildTargets = new string[]{nativeTarget, testTarget};
proj.SetBuildProperty(buildTargets, "ENABLE_BITCODE", "NO");
File.WriteAllText(projPath, proj.WriteToString());
}
}
I too had the same issue "splash screen stuck" right after launch....
I solved this issue. Please use the below code.
Tested in Unity 5.4.1p2 and Xcode 7.3.
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using UnityEditor.Callbacks;
#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif
public class Postprocessor : AssetPostprocessor
{
#if UNITY_IOS
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
{
if (buildTarget == BuildTarget.iOS)
{
string projPath = path + "/Unity-iPhone.xcodeproj/project.pbxproj";
PBXProject proj = new PBXProject();
proj.ReadFromString(File.ReadAllText(projPath));
string target = proj.TargetGuidByName("Unity-iPhone");
proj.SetBuildProperty(target, "ENABLE_BITCODE", "false");
File.WriteAllText(projPath, proj.WriteToString());
// Add url schema to plist file
string plistPath = path + "/Info.plist";
PlistDocument plist = new PlistDocument();
plist.ReadFromString(File.ReadAllText(plistPath));
// Get root
PlistElementDict rootDict = plist.root;
rootDict.SetBoolean("UIRequiresFullScreen",true);
plist.WriteToFile(plistPath);
}
}
#endif
}
In fact OnPostprocessBuild is always called, so you don't have to put anything in post export method field, which is designed for more specific methods.

Dynamically Load and Activate a dataset (vuforia and unity)

I want to make a system that I can use to download various targets dynamically from my website without using "Cloud" system.
I also want to save the dataset to .xml and .dat formats which I want to activate from my saving device.
There are a lot of methods and pages to doing that with vuforia and unity, but unfortunately when I test it I receive an error for all of them.
It seems that i have made a mistake in my code or a vuforia class was changed.
For instance please look this link:
https://developer.vuforia.com/library/articles/Solution/Unity-Load-DataSet-from-SD-Card
I got Error: Using Vuforia;
I placed the .xml and .dat files in "Application.persistentDataPath + "/" + "Building1.xml"
i used this Script "DataSetLoadBehavior" that attached "AR Camera and placed my code in it. I got an Error:
NullReferenceException: Object reference not set to an instance of an
object DataSetLoadBehaviour.OnInitialized () (at Assets/Qualcomm
Augmented Reality/Scripts/DataSetLoadBehaviour.cs:49)
DataSetLoadBehaviour.Start () (at Assets/Qualcomm Augmented
Reality/Scripts/DataSetLoadBehaviour.cs:80)
My code is this:
unity 4.2 pro and vuforia 2.8.9 or 3.0.9
/*==============================================================================
Copyright (c) 2010-2014 Qualcomm Connected Experiences, Inc.
All Rights Reserved.
Confidential and Proprietary - Qualcomm Connected Experiences, Inc.
==============================================================================*/
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This behaviour allows to automatically load and activate one or more DataSet on startup
/// </summary>
public class DataSetLoadBehaviour : DataSetLoadAbstractBehaviour
{
[HideInInspector, SerializeField]
public List<string> mDataSetsToActivate2 = new List<string>();
[SerializeField, HideInInspector]
public List<string> mDataSetsToLoad2 = new List<string>();
protected DataSetLoadBehaviour()
{
}
private void OnDestroy()
{
QCARAbstractBehaviour behaviour = (QCARAbstractBehaviour) UnityEngine.Object.FindObjectOfType(typeof(QCARAbstractBehaviour));
if (behaviour != null)
{
}
}
public void OnInitialized()
{
if (QCARRuntimeUtilities.IsQCAREnabled())
{
foreach (string str in this.mDataSetsToLoad2)
{
if (!DataSet.Exists(str, QCARUnity.StorageType.STORAGE_ABSOLUTE))
{
Debug.LogError("Data set " + str + " does not exist.");
}
else
{
ImageTracker tracker = TrackerManager.Instance.GetTracker<ImageTracker>();
DataSet dataSet = tracker.CreateDataSet();
if (!dataSet.Load(str))
{
Debug.LogError("Failed to load data set " + str + ".");
}
else if (this.mDataSetsToActivate2.Contains(str))
{
tracker.ActivateDataSet(dataSet);
}
}
}
}
}
public void OnTrackablesUpdated()
{
}
private void Start()
{
QCARAbstractBehaviour behaviour = (QCARAbstractBehaviour) UnityEngine.Object.FindObjectOfType(typeof(QCARAbstractBehaviour));
if (behaviour != null)
{
mDataSetsToLoad2.Add(Application.persistentDataPath + "/" + "Building1.xml");
OnInitialized();
}
}
public override void AddOSSpecificExternalDatasetSearchDirs()
{
#if UNITY_ANDROID
if (Application.platform == RuntimePlatform.Android)
{
// Get the external storage directory
AndroidJavaClass jclassEnvironment = new AndroidJavaClass("android.os.Environment");
AndroidJavaObject jobjFile = jclassEnvironment.CallStatic<AndroidJavaObject>("getExternalStorageDirectory");
string externalStorageDirectory = jobjFile.Call<string>("getAbsolutePath");
// Get the package name
AndroidJavaObject jobjActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
string packageName = jobjActivity.Call<string>("getPackageName");
// Add some best practice search directories
//
// Assumes just Vufroria datasets extracted to the files directory
AddExternalDatasetSearchDir(externalStorageDirectory + "/Android/data/" + packageName + "/files/");
// Assume entire StreamingAssets dir is extracted here and our datasets are in the "QCAR" directory
AddExternalDatasetSearchDir(externalStorageDirectory + "/Android/data/" + packageName + "/files/QCAR/");
}
#endif //UNITY_ANDROID
}
void Update()
{
}
}
Yeah, Vuforia has has changed a lot.
You will now have to include Vuforia as a header in order for it to work
using Vuforia;
Hope this works.
If it says Vuforia hasn't been found it's probably because you haven't imported the Unitypackage for Vuforia. You can follow these instructions.
Also, I believe you haven't followed the steps to Migrating your Unity Project. The new Vuforia doesn't support ImageTracker anymore, hence you will have to change all instances of ImageTracker to ObjectTracker

Categories