Files
cursebreaker-parser-rust/cursebreaker-parser/examples/custom_component.rs
2026-01-02 14:00:42 +00:00

102 lines
3.1 KiB
Rust

//! Example demonstrating how to define custom Unity MonoBehaviour components
//! using the #[derive(UnityComponent)] macro.
use cursebreaker_parser::{yaml_helpers, ComponentContext, UnityComponent};
/// Custom Unity MonoBehaviour component for playing sound effects
///
/// This mirrors the C# PlaySFX MonoBehaviour:
/// ```csharp
/// public class PlaySFX : MonoBehaviour
/// {
/// [SerializeField] float volume;
/// [SerializeField] float startTime;
/// [SerializeField] float endTime;
/// [SerializeField] bool isLoop;
/// }
/// ```
#[derive(Debug, Clone, UnityComponent)]
#[unity_class("PlaySFX")]
pub struct PlaySFX {
#[unity_field("volume")]
pub volume: f64,
#[unity_field("startTime")]
pub start_time: f64,
#[unity_field("endTime")]
pub end_time: f64,
#[unity_field("isLoop")]
pub is_loop: bool,
}
/// Another example - a custom damage component
#[derive(Debug, Clone, UnityComponent)]
#[unity_class("DamageDealer")]
pub struct DamageDealer {
#[unity_field("damageAmount")]
pub damage_amount: f64,
#[unity_field("damageType")]
pub damage_type: String,
#[unity_field("canCrit")]
pub can_crit: bool,
#[unity_field("critMultiplier")]
pub crit_multiplier: f64,
}
fn main() {
println!("Custom Unity Component Example");
println!("===============================\n");
println!("Defined custom components:");
println!(" - PlaySFX: volume, start_time, end_time, is_loop");
println!(" - DamageDealer: damage_amount, damage_type, can_crit, crit_multiplier\n");
println!("These components are automatically registered via the inventory crate.");
println!("When parsing Unity files, they will be recognized and parsed automatically.\n");
// Demonstrate parsing from YAML
let yaml_str = r#"
volume: 0.75
startTime: 1.5
endTime: 3.0
isLoop: 1
"#;
let yaml: serde_yaml::Value = serde_yaml::from_str(yaml_str).unwrap();
let mapping = yaml.as_mapping().unwrap();
// Create a dummy context
use cursebreaker_parser::{ComponentContext, FileID};
let ctx = ComponentContext {
type_id: 114,
file_id: FileID::from_i64(12345),
class_name: "PlaySFX",
entity: None,
linking_ctx: None,
yaml: mapping,
};
// Parse the component
if let Some(play_sfx) = PlaySFX::parse(mapping, &ctx) {
println!("Successfully parsed PlaySFX component:");
println!(" volume: {}", play_sfx.volume);
println!(" start_time: {}", play_sfx.start_time);
println!(" end_time: {}", play_sfx.end_time);
println!(" is_loop: {}", play_sfx.is_loop);
} else {
println!("Failed to parse PlaySFX component");
}
println!("\nTo use in your own code:");
println!(" 1. Define a struct matching your C# MonoBehaviour fields");
println!(" 2. Add #[derive(UnityComponent)] to the struct");
println!(" 3. Add #[unity_class(\"YourClassName\")] to specify the Unity class name");
println!(" 4. Add #[unity_field(\"fieldName\")] to each field");
println!(" 5. The component will be automatically registered and parsed!");
}