Skip to content
Snippets Groups Projects
Commit 0a983674 authored by Heine, Eric R's avatar Heine, Eric R
Browse files

Added a bunch of other scripts that we share between projects.

parent ee65ecfd
No related branches found
No related tags found
No related merge requests found
Showing
with 675 additions and 0 deletions
fileFormatVersion: 2
guid: e195b35d21293d44485eccdaae5aa7d1
folderAsset: yes
timeCreated: 1510599368
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using Shared.ScriptableVariables;
namespace Shared.ConfigSetter {
// Component to load configuration settings from an ini fileand apply them to various ScriptableVariables
// Depends on ScriptableVariable package
public class ConfigSetter : MonoBehaviour {
[Tooltip("Any Boolean settings to load")]
public List<BooleanVariable> boolSettings = new List<BooleanVariable>();
[Tooltip("Any Float settings to load")]
public List<FloatVariable> floatSettings = new List<FloatVariable>();
[Tooltip("Any Int settings to load")]
public List<IntVariable> intSettings = new List<IntVariable>();
[Tooltip("Any String settings to load")]
public List<StringVariable> stringSettings = new List<StringVariable>();
[Tooltip("Event to fire when config values are loaded")]
public UnityEvent configLoaded;
[Tooltip("The subfolder (in StreamingAssets) where the config file is located.")]
public string configFileSubfolder = "./Config";
[Tooltip("The name of the config file to load.")]
public string configFilename = "config";
[Tooltip("Should the settings be loaded on Start?")]
public bool loadOnStart = true;
//---------------------------------------------------------------------------
void Start() {
if (loadOnStart) {
LoadSettings();
}
}
//---------------------------------------------------------------------------
public void LoadSettings() {
string pathToConfig = System.IO.Path.Combine(Application.streamingAssetsPath, configFileSubfolder);
var parser = new IniParser(pathToConfig);
if (parser.DoesExist(configFilename)) {
LoadSettings(parser);
}
// The config file doesn't exist, so create one from the current variable values
else {
SaveSettings(parser);
}
// Let anyone who cares know that the configuration has been loaded
if (configLoaded != null) {
configLoaded.Invoke();
}
}
//---------------------------------------------------------------------------
private void LoadSettings(IniParser parser) {
parser.Load(configFilename);
// Apply the boolean settings
foreach (var variable in boolSettings) {
var value = parser.Get(variable.name);
if (!string.IsNullOrEmpty(value)) {
variable.Value = Convert.ToBoolean(value);
}
}
// Apply the float settings
foreach (var variable in floatSettings) {
var value = parser.Get(variable.name);
if (!string.IsNullOrEmpty(value)) {
variable.Value = Convert.ToSingle(value);
}
}
// Apply the int settings
foreach (var variable in intSettings) {
var value = parser.Get(variable.name);
if (!string.IsNullOrEmpty(value)) {
variable.Value = Convert.ToInt32(value);
}
}
// Apply the string settings
foreach (var variable in stringSettings) {
variable.Value = parser.Get(variable.name);
}
}
//---------------------------------------------------------------------------
private void SaveSettings(IniParser parser) {
// Save boolean settings
foreach (var variable in boolSettings) {
parser.Set(variable.name, variable.Value.ToString());
}
// Save float settings
foreach (var variable in floatSettings) {
parser.Set(variable.name, variable.Value.ToString());
}
// Save int settings
foreach (var variable in intSettings) {
parser.Set(variable.name, variable.Value.ToString());
}
// Save string settings
foreach (var variable in stringSettings) {
parser.Set(variable.name, variable.Value);
}
parser.Save(configFilename);
}
}
}
fileFormatVersion: 2
guid: 676e55664caf8524db8f281365b01853
timeCreated: 1510606896
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
/*
.Ini file Parser
Author: Tristan 'Kennyist' Cunningham - www.tristanjc.com
Date: 13/04/2014
License: Creative commons ShareAlike 3.0 - https://creativecommons.org/licenses/by-sa/3.0/
*/
using UnityEngine;
using System.Collections;
using System.IO;
namespace Shared.ConfigSetter {
/// <summary>
/// An .ini file parser that Creates and edits .ini files, With functions to fetch and delete values.
/// </summary>
public class IniParser {
private ArrayList keys = new ArrayList();
private ArrayList vals = new ArrayList();
private ArrayList comments = new ArrayList();
private string path = Application.dataPath + "/../Config/";
/// <summary>
/// Initializes a new instance of the <see cref="IniParser"/> class without loading a file.
/// </summary>
public IniParser(string relativePathToConfigFile){
//Debug.Log("Current directory: " + Directory.GetCurrentDirectory());
//Debug.Log("Application persistent data path: " + Application.persistentDataPath);
//Debug.Log("Application data path: " + Application.dataPath);
path = relativePathToConfigFile;
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="IniParser"/> class with loading a file.
/// </summary>
/// <param name="file">Name of the file you want to load.</param>
public IniParser(string file, string relativePathToConfigFile){
path = relativePathToConfigFile;
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
Load(file);
}
/// <summary>
/// Removes data where the key does not match the prefix
/// </summary>
/// <param name="prefix">The string to match before the delimiting ':' character</param>
public void PruneUsingKeyPrefix(string prefix) {
for (int i = keys.Count - 1; i >= 0; --i) {
string key = keys[i].ToString();
string[] splitKey = key.Split(':');
if (!splitKey[0].Contains(prefix)) {
keys.RemoveAt(i);
vals.RemoveAt(i);
comments.RemoveAt(i);
} else {
keys[i] = splitKey[1];
}
}
}
/// <summary>
/// Returns true if the file exists, or false if it doesnt.
/// </summary>
/// <param name="file">The selected file.</param>
public bool DoesExist(string file){
//return File.Exists(Application.persistentDataPath + "/" + file + ".ini") ? true : false;
return File.Exists(GetFullPath(file)) ? true : false;
}
public string GetFullPath(string rootFileName) {
return System.IO.Path.Combine(path, rootFileName + ".ini");
}
/// <summary>
/// Set the variable and value if they dont exist. Updates the variables value if does exist.
/// </summary>
/// <param name="key">The variable name</param>
/// <param name="val">The value of the variable</param>
public void Set(string key, string val){
var index = keys.IndexOf(key);
if (index != -1) {
vals[index] = val;
return;
}
keys.Add(key);
vals.Add(val);
comments.Add(System.String.Empty);
}
/// <summary>
/// Set the variable and value if they dont exist including a comment. Updates the variables value and comment if does exist.
/// </summary>
/// <param name="key">The variable name</param>
/// <param name="val">The value of the variable</param>
/// <param name="comment">The comment of the variable</param>
public void Set(string key, string val, string comment){
var index = keys.IndexOf(key);
if (index != -1) {
vals[index] = val;
comments[index] = comment;
return;
}
keys.Add(key);
vals.Add(val);
comments.Add(comment);
}
/// <summary>
/// Returns the value for the input variable.
/// </summary>
/// <param name="key">The variable name.</param>
public string Get(string key){
for(int i = 0; i < keys.Count; i++){
if(keys[i].Equals(key)){
return vals[i].ToString();
}
}
return System.String.Empty;
}
/// <summary>
/// Returns the Key, Value and comment of the choosen variable.
/// </summary>
/// <returns>String array containing the 3 values</returns>
/// <param name="key">The variable name.</param>
public string[] GetLine(string key){
string[] list = new string[2];
for(int i = 0; i < keys.Count; i++){
if(keys[i].Equals(key)){
list[0] = keys[i].ToString();
list[1] = vals[i].ToString();
list[2] = comments[i].ToString();
return list;
}
}
return list;
}
/// <summary>
/// Removes the selected Variable including its value and comment.
/// </summary>
/// <param name="key">The variable name.</param>
public void Remove(string key){
var index = keys.IndexOf(key);
if (index != -1){
keys.RemoveAt(index);
vals.RemoveAt(index);
comments.RemoveAt(index);
return;
}
Debug.LogWarning("Key not found");
}
/// <summary>
/// Save the specified file.
/// </summary>
/// <param name="file">The file name.</param>
public void Save(string file){
StreamWriter wr = new StreamWriter(GetFullPath(file));
for(int i = 0; i < keys.Count; i++){
if(comments[i].Equals(System.String.Empty)){
wr.WriteLine(keys[i] +"="+ vals[i]);
} else {
wr.WriteLine(keys[i] +"="+ vals[i]+" //"+comments[i]);
}
}
wr.Close();
//Debug.Log(GetFullPath(file) + " Saved");
}
/// <summary>
/// Load the specified file.
/// </summary>
/// <param name="file">The file name.</param>
public void Load(string file){
keys = new ArrayList();
vals = new ArrayList();
comments = new ArrayList();
string line = System.String.Empty, dir = GetFullPath(file);
int offset = 0, comment = 0;
try{
using(StreamReader sr = new StreamReader(dir)){
while((line = sr.ReadLine()) != null){
offset = line.IndexOf("=");
comment = line.IndexOf("//");
if(offset > 0){
if(comment != -1){
Set(line.Substring(0,offset),line.Substring(offset+1,(comment - (offset+1))),line.Substring(comment+1));
} else {
Set(line.Substring(0,offset),line.Substring(offset+1));
}
}
}
sr.Close();
//Debug.Log(file + ".ini Loaded");
}
} catch(IOException e){
Debug.Log("Error opening " + GetFullPath(file));
Debug.LogWarning(e);
}
}
/// <summary>
/// How many keys are stored.
/// </summary>
public int Count(){
return keys.Count;
}
}
}
fileFormatVersion: 2
guid: a7d034d8dee7d2f4c83e3d67f75fc760
timeCreated: 1510606902
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: f585f51ad02755348bfdbfd764fc5b7a
folderAsset: yes
timeCreated: 1510599155
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using Shared.ScriptableVariables;
namespace Shared.EventLog {
// A generic list of events to write to a log file
// Depends on ScriptableVariable package
[CreateAssetMenu(menuName = "Scriptable Objects/Event Log")]
public class EventLog : ScriptableVariable {
readonly List<KeyValuePair<string, string>> events = new List<KeyValuePair<string, string>>();
private DateTime startTime = DateTime.Now;
// ---------------------------------------------------------------------------
// Add an event to the log
public void Add(string key, string value) {
events.Add(new KeyValuePair<string, string>(DateTime.Now.Subtract(startTime).TotalSeconds.ToString() + "," + key, value));
}
// ---------------------------------------------------------------------------
[ContextMenu("Clear")]
// Clear out all previous events in the log
public void Clear() {
events.Clear();
startTime = DateTime.Now;
}
// ---------------------------------------------------------------------------
// Write out all event logs to the given file in the given directory
// Will create the directory if it doesn't exist
public void WriteToFile(string directory, string filename) {
string csv = string.Join(
System.Environment.NewLine,
events.Select(d => d.Key + "," + d.Value).ToArray()
);
#if UNITY_ANDROID
directory = Application.persistentDataPath + "/" + directory;
#endif
if (!Directory.Exists(directory)) {
Directory.CreateDirectory(directory);
}
directory += "/" + filename;
File.WriteAllText(directory, csv);
}
}
}
fileFormatVersion: 2
guid: 66879b8b4bcd92e48aceed1616c19659
timeCreated: 1510685488
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
namespace Shared.EventLog {
// Stops event logging when this Component is destroyed
public class EventLogAutoEnder : MonoBehaviour {
[Tooltip("The event log controller that should stop logging when this component is destroyed")]
public EventLogController controller;
//--------------------------------------------------------------------------
void OnDestroy() {
controller.StopLogging();
}
}
}
fileFormatVersion: 2
guid: 4962af3dcfbf0114193834096bc4d12f
timeCreated: 1510685488
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System.Collections;
using UnityEngine;
namespace Shared.EventLog {
// Starts event logging one frame after this Component starts
public class EventLogAutoStarter : MonoBehaviour {
[Tooltip("The event log controller that should start logging when this component starts")]
public EventLogController controller;
//--------------------------------------------------------------------------
IEnumerator Start() {
// Give all normal code a chance to finish
yield return null;
controller.StartLogging();
}
}
}
fileFormatVersion: 2
guid: e1f409d937924e1428486b1611d7b737
timeCreated: 1510685488
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System;
using UnityEngine;
using Shared.ScriptableVariables;
namespace Shared.EventLog {
// A Component in charge of starting an event log and writing it to a file on completion
// Depends on ScriptableVariable package
public class EventLogController : MonoBehaviour {
[Tooltip("The event log to write out to a file")]
public EventLog eventLog;
[Tooltip("Event to fire when logging has started")]
public GameEvent loggingStarted;
[Tooltip("The filename of the log file generated by an event log")]
public StringVariable logFileName;
[Tooltip("The output directory to write the log file to")]
public StringVariable outputDirectory;
private DateTime startTime = DateTime.Now;
private bool isLogging = false;
//--------------------------------------------------------------------------
// Clear any previous event logs, add a start time event log, and inform anyone who is listening that we are now logging events
public void StartLogging() {
isLogging = true;
eventLog.Clear();
startTime = DateTime.Now;
eventLog.Add("start-time", startTime.ToString("hh:mm:ss"));
loggingStarted.Raise();
}
//--------------------------------------------------------------------------
// Add an end time event log, write the event log out to file, and clear the event log of events
public void StopLogging() {
if (isLogging) {
DateTime endTime = DateTime.Now;
eventLog.Add("end-time", endTime.ToString("hh:mm:ss"));
eventLog.WriteToFile(outputDirectory.Value, logFileName.Value + "." + endTime.ToString("MM-dd-yyy-hhmmss") + ".csv");
eventLog.Clear();
isLogging = false;
}
}
}
}
fileFormatVersion: 2
guid: c61f293680e58654b8b2e7d0ee062518
timeCreated: 1510685488
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
using Shared.ScriptableVariables;
namespace Shared.EventLog {
// Write something to the event log on a fixed interval
public abstract class IntervalEventLogger : MonoBehaviour {
[Tooltip("Amount of time (in seconds) between event logs")]
public FloatVariable logDelay;
[Tooltip("Event log to log events to")]
public EventLog eventLog;
private float timeUntilNextLog = 0.0f;
//---------------------------------------------------------------------------
void Update() {
timeUntilNextLog -= Time.deltaTime;
if (timeUntilNextLog <= 0.0f) {
timeUntilNextLog = logDelay.Value;
LogEvent();
}
}
//---------------------------------------------------------------------------
// Override to implement what event you want to log on an interval
protected abstract void LogEvent();
}
}
fileFormatVersion: 2
guid: a097317eb1478fb4e90db374d6f9fd35
timeCreated: 1510686998
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using UnityEngine;
namespace Shared.EventLog {
// Log the position and rotation of a given Transform
public class PositionRotationLogger : IntervalEventLogger {
[Tooltip("Transform to log position and rotation for")]
public Transform transformToLog;
//---------------------------------------------------------------------------
// Add the Transform's position and rotation to the event log
protected override void LogEvent() {
eventLog.Add("Player Position", "\"" + transformToLog.position.ToString() + "\"");
eventLog.Add("Player Rotation", "\"" + transformToLog.rotation.eulerAngles.ToString() + "\"");
}
}
}
fileFormatVersion: 2
guid: 05235afcdb8a536488366f4265a7afb2
timeCreated: 1510686998
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 3cae5d7dc3d654949afa03e8f91bc09f
folderAsset: yes
timeCreated: 1511204823
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
using System.Collections.Generic;
using UnityEngine;
using Shared.ScriptableVariables;
namespace Shared.EventLog {
// Log the values of a list of BooleanVariables every interval
// Depends on ScriptableVariable package
public class BooleanVariableLogger : IntervalEventLogger {
[Tooltip("Transform to log position and rotation for")]
public List<BooleanVariable> variables = new List<BooleanVariable>();
//---------------------------------------------------------------------------
// Add all of the BooleanVariables to the event log
protected override void LogEvent() {
foreach (var variable in variables) {
eventLog.Add(variable.name, "\"" + variable.Value + "\"");
}
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment