- Home /
Store different int values in an instantiated prefab
I'm working on my first VR game with a friend of mine, and I'm currently coding in the mag system. One of the parts of this involves ammo count. I need a way to have a default count of ammo (in this case 30 ill just use a pub variable and then I can attach the modular script to each specific mag to set it) and then have the count in each prefab deplete separately such that you don't run black on ammo, go to reload and load in an empty mag because they all run off the same script. Also, while I'm on this topic, I'd like to ask about having A: the value of ammoCount correspond to the amount of rounds that actually get rendered in the mag (for windowed PMAG's, Lancers, etc.) and B: putting a follower spring on a spline and have that move as the count goes down and the follower moves up towards the top. Anyways, that's enough rambling about my stupidity, if anybody's got an answer, it'd be much appreciated!
Thanks for your time and I hope I didn't bore you to death lmao
Answer by HammockHead21 · Sep 25, 2021 at 09:53 PM
You can use prefab variants https://docs.unity3d.com/Manual/PrefabVariants.html or you could create a factory class that sets the defaults values so instead of calling Instantiate directly you could do the following:
public class AmmoFactory : Monobehaviour
{
[SerializeField] Ammo ammoPrefab;
[Serializable]
public struct AmmoSpec
{
public string type;
public int rounds;
}
[SerializeField] AmmoSpec[] editorAmmoSpecs;
Dictionary<string, AmmoSpec> ammoSpecs;
void Awake()
{
ammoSpecs= new Dictionary<string, AmmoSpec>();
foreach (var ammoSpec in editorAmmoSpecs)
{
ammoSpecs.Add(ammoSpec.type, ammoSpec);
}
}
public Ammo Create(string type)
{
if (ammoSpecs.TryGetValue(type, out AmmoSpec ammoSpec))
{
Ammo ammo = Instantiate(ammoPrefab).GetComponent<Ammo>();
ammo.SetSpec(ammoSpec);
return ammo;
}
return null;
}
}
I've read a little bit of the doc, and it makes sense already. Thank you so much for linking it!
@HammockHead21 would the prefab variants be a modular script? such that i can create an infinite amount without affecting the way it works? i would assume so but you never know