Scripting API
For developers who need mock data at runtime - automated testing, procedural content, live dashboards, or CI pipelines - MockMagic provides a clean static API. Every feature available in the Editor window is also available from code.
Assembly reference: Add a reference to com.wetzold.mock-magic in your .asmdef file, or place your scripts in a folder without an assembly definition. The namespace remains MockMagic.
Namespace: using MockMagic;
Simple Data from Code
The Mock static class provides one method per data type, plus batch variants.
Single Values
using MockMagic;
string name = Mock.Name(); // "Sarah Johnson"
string email = Mock.Email(); // "marcus.patel@outlook.com"
string phone = Mock.Phone(); // "+1 (425) 738-2914"
int age = Mock.Age(); // 34
string address = Mock.FullAddress(); // "1847 Oak Ave, Seattle, WA 98101"
string guid = Mock.Guid(); // "a3f8b2c1-d4e5-4f6a-8b9c-0d1e2f3a4b5c"
float pct = Mock.Percentage(); // 87.45
bool flag = Mock.Boolean(); // true
string lorem = Mock.LoremIpsum(20); // 20 words of lorem ipsum
UnityEngine.Color color = Mock.Color();// Random RGB color
Batch Values
Common value generators provide plural batch methods that return arrays, for example:
string[] names = Mock.Names(50);
string[] emails = Mock.Emails(100);
int[] ages = Mock.Ages(25);
string[] cities = Mock.Cities(10);
Generic Dispatch
Use Mock.Generate() when the data type is determined at runtime:
// Single value
string value = Mock.Generate(SimpleDataType.Email);
// Batch
string[] values = Mock.Generate(SimpleDataType.Email, 50);
Random Enum Values
Generate random values of any enum type:
MyEnum randomValue = Mock.Enum<MyEnum>();
MyEnum[] randomValues = Mock.Enums<MyEnum>(10);
ID Counter
Mock.Id() returns auto-incrementing integers, and Mock.Seed restarts them at 1. Set the next value with:
Mock.ResetIdCounter(1); // Next Id() call returns 1; an active seed is kept
Determinism & Seeding
Call Mock.Seed(int) once at the top of a deterministic run; pair it with Mock.UseDateReference(...) so date-, time- and timestamp-based helpers stay reproducible across days.
Mock.Seed(12345); // seeds MockRandom + UnityEngine.Random
Mock.UseDateReference(new DateTime(2026, 1, 1)); // freeze "now" for date helpers
string a = Mock.Email(); // reproducible
string b = Mock.Date(); // reproducible
Mock.ResetSeed(); // restore unseeded randomness; date reference is separate
Mock.UseDateReference(null); // restore wall-clock date reference
Import System for DateTime, and put both cleanup calls in a finally block when generation may throw. ResetSeed leaves the date reference alone, and it gives UnityEngine.Random fresh randomness when Mock.Seed had seeded it. For a moving reference, pass a function to Mock.UseDateReferenceProvider instead.
Format & Hash Helpers
Shape any string with a tiny pattern language: ‘#’= digit, ‘?’= lowercase letter, ‘*’= alphanumeric, ‘\’= escape the next character. Phone, SSN, ZIP and MAC helpers all use it internally.
string sku = Mock.Format("AB-####-???"); // "AB-2741-xqp"
string sha = Mock.Hash(); // 40-char hex (SHA-1 length)
string code = Mock.AlphaNumeric(8); // "k4j9pq7m"
string tag = Mock.Letters(5, upperCase: true);
Template Tokens & Custom Generators
Every SimpleDataType is a built-in token. Unknown tokens are left in place so they're easy to spot during debugging. Register your own tokens - or full typed generators - to extend the system without forking the package; use Mock.HasToken and Mock.UnregisterToken for registry checks and cleanup.
string row = Mock.Parse("{{firstName}} <{{email}}> id={{unique}}");
Mock.RegisterToken("orderRef", () => "ORD-" + Mock.Format("######"));
Mock.RegisterGenerator<int>("score", () => MockRandom.Range(1, 101));
int s = Mock.Get<int>("score");
string r = Mock.Parse("Reference: {{orderRef}}");
UnregisterToken(name) removes its template token and every typed generator registered under the same name. Matching is case-insensitive. Use distinct custom names and unregister only the registrations owned by your workflow.
Probabilistic Nulls
Drop-in nullability for stress-testing consumers. The same extension set also provides seeded list helpers such as PickRandom() and Shuffle():
string maybeAddress = Mock.FullAddress().OrNull(0.3f); // reference types
int? maybeAge = Mock.Age().OrNullable(0.2f); // value types -> Nullable<T>
float maybeScore = Mock.Float().OrDefault(0.1f); // any T -> default(T)
Object Builders
MockPerson.New() groups generated person fields into one record - email and username are derived from the drawn name, and the address parts cohere into a single line. Mock.Datasets.Person() is a friendly alias for the same generator.
MockPerson derives birth dates from Mock.UseDateReference, so seeded people repeat exactly, and Age is always the exact age on the reference date, including leap-day birthdays.
MockPerson p = MockPerson.New();
MockPerson[] roster = MockPerson.New(50);
MockOf<T> is a delegate-based fluent builder for any POCO. No reflection, no expression trees - IL2CPP/AOT safe.
User[] users = MockOf<User>
.New(() => new User())
.Set((u, i) => u.Id = i + 1)
.Set(u => u.Name = Mock.Name())
.Set(u => u.Email = Mock.Email())
.UseSeed(42)
.Generate(100);
UseSeed seeds each Generate or GenerateLazy pass on its own and then restores the previous random state, seed and ID counter, including UnityEngine.Random. Code around the builder keeps its own sequence, so no ResetSeed call is needed afterward.
Regional Data From Code
MockLocales.All lists the available data profiles. Resolve a profile through MockLocales.Get(id) and inspect GetCoverage(SimpleDataType) or GetLabelCoverage(LabelPreset) before requesting a regional field. Unknown IDs fail explicitly. Mock.CurrentLocale exposes the current synchronous selection.
using (Mock.LocaleScope("de-DE"))
{
string[] names = Mock.Names(10);
string row = Mock.Parse("{{name}} | {{phone}}");
MockPerson person = MockPerson.New();
}
The scope applies to existing direct methods, plural methods and built-in template tokens, then restores the caller's locale. Tokens remain independent draws; use a person record for related fields. Locale selection does not reseed randomness, reset IDs or change the date reference. Dispose an ambient scope before awaiting, yielding or suspending a coroutine.
Add UseLocale(id) alongside UseSeed on a typed builder when that builder needs its own profile. An unconfigured builder inherits its caller's locale. Each generation operation captures one immutable profile and restores the caller's selection after factories, setters and finishers, including failures and before each lazy result is yielded.
User[] users = MockOf<User>.New(() => new User())
.UseLocale("de-DE")
.UseSeed(42)
.Set((user, index) => user.Id = index + 1)
.Set(user => user.Name = Mock.Name())
.Generate(10);
Use an explicit profile for a label consumer that outlives a temporary scope. GenerateLabels accepts a MockLocale argument after the count. GetFiniteLabelCount reports the selected profile's finite vocabulary size instead of assuming that every city, color or region list has the same length.
MockLocale german = MockLocales.Get("de-DE");
string[] months = MockSeries.GenerateLabels(
LabelPreset.MonthsShort, 12, german);
For streams, configure DataLocaleId before starting, or call MockStreaming.Configure(localeId: "de-DE", labelPreset: LabelPreset.Months). ActiveLocale and ActiveLocaleId describe the running snapshot and are null while stopped. EmitOnce uses that snapshot while running and configured data while stopped. Repeating Start while already running does not recapture pending settings.
Ssn remains explicitly US-specific. Selecting another locale does not convert it into a different national identifier. Phone(true) requires an explicitly supported fictional-number range; ordinary phone-format metadata does not establish one.
Project Data Profiles
A project profile can inherit a built-in locale and replace selected values or related locations. Registration snapshots the definition, so later input-array changes do not alter captured profiles. Built-in profile IDs and aliases cannot be replaced.
MockLocale studio = MockLocales.Register(
new MockLocaleDefinition("studio", "Studio", "de-DE")
.SetValues(SimpleDataType.FirstName, "Mara")
.SetLocations(new MockLocaleLocation(
"Berlin", "Berlin", "10115")));
Use the returned profile with Mock.LocaleScope(studio). SetNameOrder changes family-name order and its separator; WithoutAddresses(reason) explicitly marks complete addresses unavailable. Unregister removes future lookup without invalidating captured profiles. Register custom definitions during application startup because runtime-session reset clears custom registrations.
Image & Themed Text Helpers
*Mock.ImageUrl(width, height) - random picsum.photos URL.
*Mock.PlaceholderImageUrl(width, height, bg, fg, text) - placehold.co URL with optional colours and label.
*Mock.SvgDataUri(width, height, fill, label) - self-contained, offline SVG data URI.
*Mock.HackerPhrase() - tech-flavoured activity-log line, e.g. "Try parsing the SSL sensor, maybe it will reboot the digital bus!". Use Mock.HackerAdjective(), Mock.HackerNoun(), Mock.HackerVerb(), and Mock.HackerIngVerb() when you need individual themed words.
*Mock.Review(minWords, maxWords) - short product-style review string for e-commerce mocks.
Series Data from Code
The MockSeries static class generates patterned datasets.
Full-Featured Generation
using MockMagic;
MockDataPoint[] data = MockSeries.Generate(
pattern: SeriesPattern.TrendingUp,
count: 12,
min: 0f,
max: 100f,
noise: 0.15f,
labelPreset: LabelPreset.MonthsShort
);
// Each point has: data[i].Label, data[i].Value, data[i].SeriesName, etc.
Multi-Series Generation
MockDataPoint[][] multiData = MockSeries.GenerateMultiSeries(
pattern: SeriesPattern.Seasonal,
seriesCount: 3,
pointCount: 12,
min: 0f,
max: 100f,
noise: 0.1f,
labelPreset: LabelPreset.MonthsShort,
seriesNames: new[] { "Revenue", "Costs", "Profit" }
);
// multiData[0] = Revenue series, multiData[1] = Costs series, etc.
Convenience Methods
Short-form methods with sensible defaults:
MockDataPoint[] data = MockSeries.Linear(); // 12 points, 0–100, low noise
MockDataPoint[] data = MockSeries.Sine(); // Sine wave
MockDataPoint[] data = MockSeries.TrendingUp(); // Upward trend
MockDataPoint[] data = MockSeries.TrendingDown(); // Downward trend
MockDataPoint[] data = MockSeries.Seasonal(); // Seasonal pattern
MockDataPoint[] data = MockSeries.BellCurve(); // Normal distribution
MockDataPoint[] data = MockSeries.Random(); // Random values
MockDataPoint[] data = MockSeries.Stepped(); // Staircase
MockDataPoint[] data = MockSeries.Sparse(); // 70% zeros
MockDataPoint[] data = MockSeries.RandomWalk(); // Financial-style random walk
MockDataPoint[] data = MockSeries.Exponential(); // Exponential growth
Raw Values Only
If you only need the float array without labels:
float[] values = MockSeries.GenerateValues(
SeriesPattern.Sine, count: 50, min: -1f, max: 1f, noise: 0f
);
Custom Labels
string[] labels = MockSeries.GenerateLabels(
LabelPreset.MonthsShort, count: 12, startIndex: 0
);
// ["Jan", "Feb", "Mar", ..., "Dec"]
GenerateLabels uses a zero-based startIndex. For April, use startIndex: 3 with MonthsShort. Years and Quarters also accept startYear. To apply these labels to generated values, pass the returned array as customLabels to MockSeries.Generate with LabelPreset.Custom; Generate does not take startIndex or startYear directly.
Streaming from Code
For continuous real-time data, use the MockStreaming static convenience class or the MockStream component directly.
Using MockStreaming (Recommended)
using MockMagic;
using UnityEngine;
public class LiveDashboard : MonoBehaviour
{
private void OnEnable()
{
// Configure the stream
MockStreaming.Configure(
pattern: SeriesPattern.RandomWalk,
min: 0f,
max: 100f,
noise: 0.1f,
pointsPerEmission: 1,
labelPreset: LabelPreset.MonthsShort
);
// Register a listener
MockStreaming.Register(OnDataReceived);
// Start streaming
MockStreaming.Start(interval: 1.0f, rhythm: StreamRhythm.Constant);
}
private void OnDisable()
{
MockStreaming.Unregister(OnDataReceived);
MockStreaming.Stop();
}
private void OnDataReceived(MockDataPoint[] points)
{
foreach (MockDataPoint point in points)
{
Debug.Log($"{point.Label}: {point.Value}");
}
}
}
Using MockStream Directly
MockStream is a MonoBehaviour with full property access. MockStream.Instance is the shared stream behind MockStreaming and lives on a hidden object; MockStream components you add to scenes stream on their own and are never adopted:
MockStream stream = MockStream.Instance;
stream.Pattern = SeriesPattern.Sine;
stream.Rhythm = StreamRhythm.Burst;
stream.Interval = 0.5f;
stream.BurstCount = 5;
stream.BurstDelay = 3f;
stream.MinValue = 0f;
stream.MaxValue = 100f;
stream.Noise = 0.1f;
stream.PointsPerEmission = 3;
stream.LabelPreset = LabelPreset.WeekdaysShort;
stream.Register(OnDataReceived);
stream.OnStreamStarted += () => Debug.Log("Stream started");
stream.OnStreamStopped += () => Debug.Log("Stream stopped");
stream.StartStream();
// ... later ...
stream.StopStream();
Pair Register with Unregister in the owning component’s teardown. Retain named delegates for OnStreamStarted and OnStreamStopped so those event subscriptions can also be removed. Stop the shared stream only when your component owns its lifetime.
Set stream.CycleLength to control pattern repetition across emissions. For code that also needs clock control, stream.ClockMode uses ClockMode from ImpossibleRobert.Common.Timing: Scaled follows game time, Unscaled and Realtime ignore timeScale, and Manual emits only when EmitOnce is called. MockStreaming.Start changes only Interval and Rhythm; set MinInterval and MaxInterval explicitly for Random timing. These are code properties, not serialized MockStream Inspector controls. With LabelPreset.Custom, set stream.CustomLabels or pass customLabels to MockStreaming.Configure; an empty list falls back to Item labels.
Single Emission
Fire one emission without starting continuous streaming:
MockStreaming.EmitOnce();
// or
MockStream.Instance.EmitOnce();
Continuing a Pattern From Code
Use MockSeriesCursor when you need consecutive batches without the shared streaming component. Create one cursor for the selected SeriesPattern and cycle length, then retain it and call Next(count, min, max, noise) for each batch. Position reports how many values have been produced, Reset restarts the pattern, and ContinueFrom(lastValue) lets a random walk continue existing data. Creating a fresh cursor for every request restarts the pattern.
Export from Code
The MockExport static class converts data to formatted strings.
Exporting Series Data
using MockMagic;
MockDataPoint[] data = MockSeries.TrendingUp();
string text = MockExport.Export(data, ExportFormat.Text);
string csv = MockExport.Export(data, ExportFormat.Csv);
string json = MockExport.Export(data, ExportFormat.Json);
string code = MockExport.Export(data, ExportFormat.CSharpCode, variableName: "sales");
Exporting Multi-Series Data
MockDataPoint[][] multiData = MockSeries.GenerateMultiSeries(
SeriesPattern.Seasonal, 3, 12, 0f, 100f, 0.1f, LabelPreset.MonthsShort
);
string json = MockExport.Export(multiData, ExportFormat.Json);
Exporting Simple Data
string[] emails = Mock.Emails(20);
string csv = MockExport.Export(emails, ExportFormat.Csv);
Copy to the clipboard or save the output to a file
MockExport.CopyToClipboard(data, ExportFormat.Csv); // MockDataPoint[]
MockExport.CopyToClipboard(multiData, ExportFormat.Json); // MockDataPoint[][]
MockExport.CopyToClipboard(emails, ExportFormat.Text); // string[]
MockExport.CopyToClipboard("custom string"); // Raw string
To save from a script, write the returned string with System.IO.File.WriteAllText(path, csv), replacing csv with the desired exported string. MockExport formats the data; your code chooses the file path and performs the write. Refresh Unity's Asset Database from editor code if the file needs to appear in the Project window immediately.
Feeding MockMagic Data into Chart Guru
using MockMagic;
using ChartGuru;
using UnityEngine;
public class MockChart : MonoBehaviour
{
private ChartGraphic _chart;
private void Start()
{
// Generate mock data
MockDataPoint[] data = MockSeries.Generate(
SeriesPattern.TrendingUp, 12, 0f, 100f, 0.15f, LabelPreset.MonthsShort
);
// Build a Chart Guru chart
ChartBuilder builder = Chart.Create();
for (int i = 0; i < data.Length; i++)
{
BarMark bar = new BarMark(i, data[i].Value);
bar.CategoryLabel = data[i].Label;
builder.Add(bar);
}
Chart chart = builder
.ChartXAxisLabel("Month")
.ChartYAxisLabel("Value")
.Build();
_chart = ChartCanvasHelper.RenderToRectTransform(
chart, GetComponent<RectTransform>(), true, "MockChart"
);
}
}