- Home /
Prefab from file reference not cloned?
I'm still getting used to the way Unity does thing. So bear with me please.
I'm currently writing an RPG/strategy-style card game. The way I have organized my card system is by creating Card objects, and each Card object has one or more Ability objects tied to it. This allows me to swap out abilities on the fly or create new card type by simply trying new combinations of abilities. Each card type and ability type has been converted into a prefab for easy reuse.
The problem I've run into is modification to an ability causes the prefab (the actual file apparently) to be altered. The example I'm running into involves abilities which can be toggled. During the game, if I toggle an ability on and then exit the game, the next time I start the game all of my cards with that ability will suddenly have it initially toggled on. This seems counter-intuitive as I'd prefer the prefab to represent the initial state of the Ability and not have the altered state carry over between game sessions.
One solution I've considered but haven't tested is to create a series of dummy objects which have the prefab Ability behavior applied to them, and add these dummy objects to the card prefabs; then use these instances for the card abilities rather than the Ability prefabs. This seems like a very cumbersome solution, though, as I now have to go through each card and create these dummy game objects and apply the ability to each game object and then tie the game object back to the card... ugh.
Is there a way to get the prefab to just clone itself when referenced rather than have to go through all this work?
Answer by cirrusplay · Aug 11, 2017 at 04:29 PM
And but seconds after I write my question, I come up with a solution. I don't know if this is the best way to go about it, but it works. I'm still excited to see other people's solutions if they can find a better one, but my solution simply entails going through all of my Card abilities once the Card is initialized and cloning each Ability Game Object, then replacing the Card's ability with the new Game Object's Ability. This appears to create a clone of the Ability which is exactly what I need. Here's some code for others in the same pickle (code is contained in my Card.cs file and called from Start()):
private void CloneAbilities()
{
if (this.abilities != null && this.abilities.Length > 0)
{
for (var i = 0; i < this.abilities.Length; i++)
{
var ability = this.abilities[i];
if (ability != null)
{
var go = GameObject.Instantiate(ability);
this.abilities[i] = go.GetComponent<Ability>();
}
}
}
}