The PUN Prefab Key component provides a simple, consistent way to identify prefabs when using the Photon PUN 2+ integration.
It ensures each networked prefab has a stable string identifier (or key) that can be referenced during registration and instantiation.
1. Overview
When using Photon PUN, every networked object must be referenced by a unique name string for registration and instantiation.
By default, PUN uses the GameObject’s name, but this can become unreliable when:
Prefabs are renamed or duplicated.
Nested prefab variants share the same name.
You want to define shorter or consistent keys for external systems.
The PUNPrefabKey component solves this by providing a serialized, editor-visible field for an explicit identifier.
2. Component Reference
#if PUN_2_OR_NEWERusingUnityEngine;namespaceMegaCrush.Spawner.PunAdapter{ ///<summary> /// Attach to a prefab to give it a stable PUN key. /// Falls back to GameObject.name if empty. ///</summary>publicsealedclassPUNPrefabKey:MonoBehaviour{[SerializeField]privatestringid;publicstringId=>string.IsNullOrWhiteSpace(id)?gameObject.name:id;}}#endif
3. How It Works
When the PUN Pool Prefab Provider or PUN Bootstrap registers prefabs, it queries each prefab for a PUNPrefabKey component.
If the component exists and its id field is set, that string is used as the registration key.
If id is empty, it automatically falls back to the prefab’s GameObject.name.
This ensures the same prefab key is used consistently at both registration and instantiation.
4. Usage
Attach the component to any prefab that will be networked via Photon PUN.
Set a unique Id in the inspector (for example, Enemy_Grunt, Pickup_Medkit, etc.).
Leave empty if you want to use the prefab name as the key.
During runtime, the PUN integration uses that ID automatically when registering prefabs with the pool.
5. Benefits
Without PUNPrefabKey
With PUNPrefabKey
Prefab key = GameObject name only
Explicit, serialized key value
Fragile if renamed or duplicated
Stable even after renames
Requires matching names across scenes and assets
Independent, consistent IDs
Harder to track in large libraries
Easy to audit via inspector
6. Integration Notes
Works automatically with:
PUNPrefabRegistrar.RegisterFromScene()
PUNPoolPrefabProvider
PunBootstrap sample scene
The PUNPrefabKey does not affect local instantiation or object pooling — it only influences prefab registration and lookup.
You can safely omit it if you rely entirely on prefab names, but it’s highly recommended for larger projects or shared prefab sets.
✅ Summary
The PUN Prefab Key component helps make Photon PUN integrations robust and maintainable by decoupling network identifiers from prefab names.
Best practice:
Add a PUNPrefabKey to every networked prefab and assign a clear, stable ID.
This keeps prefab registration consistent even as your project grows.