Sunday, September 29, 2019

c# - Changing one prefab changes all other instances of that prefab too


I have made two prefabs of my enemies for my 2D game: normal and damaged. The I put several of these prefabs on scene. When enemies health <=0 I need to destroy its GameObject and then instantiate a damaged prefab on its position. But when I am doing this, all other prefabs are destroying too and damaged prefabs are instantiated on their positions. After searching this site I found out that any changes with one prefab are applying to all other prefabs on scene? Is this right?


P.S. I have edited the script where I am destroying prefab and added to it a simple check, if the prefabs renderer is visible on scene, then I need to destroy it, because all other prefabs are not visible at this moment. Do I need to check to make sure that this is the instance of the prefab is that I need every time when I want to apply to it some change?



Answer



Once a prefab has been instantiated, anything you do to that prefab should be independent of other instances of that prefab. It's more likely you have a code error that is accidentally changing all your instances. For example: How can I edit the components of an instantiated prefab? addresses editing the components of one prefab without changing any others.


You need to ensure you're referencing the specific object you're trying to change. Don't reference the prefab source, just the gameObject you want to change. If you change something that's common to all the instances, like a mesh or texture, it will affect all the instances, similar to this problem: How to make prefabs independent?


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...