Skip to content

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 the MockMagic assembly definition in your .asmdef file, or place your scripts in a folder without an assembly definition.

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

Every single-value method has a batch counterpart that returns an array:

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. Reset with:

Mock.ResetIdCounter(1); // Next Id() call returns 1; also resets shared randomness

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((DateTime?)null); // restore wall-clock date reference

Use the nullable DateTime cast when clearing the reference because UseDateReference also has a provider overload. Import System for DateTime, and put both cleanup calls in a finally block when generation may throw.

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 a token from template lookup. It does not remove a typed generator used by Get<T>; give custom registrations deliberate ownership and distinct names rather than treating token cleanup as a full registry reset.

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 currently derives its birth year from the wall clock, so UseDateReference does not control its birth dates. Age is a year-based approximation; it may differ from exact age before the generated birthday. For tests that require exact age or fixed dates, use MockOf<T> with explicit date and age setters.

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);

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"]

Streaming from Code

For continuous real-time data, use the MockStreaming static convenience class or the MockStream MonoBehaviour singleton 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 singleton MonoBehaviour with full property access:

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.

Single Emission

Fire one emission without starting continuous streaming:

MockStreaming.EmitOnce();

// or

MockStream.Instance.EmitOnce();

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); // MockDataPoint[]

MockExport.CopyToClipboard(multiData); // MockDataPoint[][]

MockExport.CopyToClipboard(emails); // string[]

MockExport.CopyToClipboard("custom string"); // Raw string

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"

);

}

}