Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Prefab instances are sharing the same data

Discussion in 'Prefabs' started by arun-muralidharan, May 6, 2023.

  1. arun-muralidharan

    arun-muralidharan

    Joined:
    Jun 8, 2020
    Posts:
    3
    Hello!

    I'm working on a 2D shmup game, and I have a general architectural question on handling prefabs.

    I have created a simple enemy prefab. To the prefab, I have attached an asset, which has the default data (health, ability, weapon, etc.). The problem is, when I have multiple instances of the same prefab, any change to one enemy, applies the change to all enemies. So, if the player kills one enemy, all enemies disappear.

    I know the problem. The asset I have attached to the enemy prefab is taken as reference, and is not copied by value when the instance is generated.

    The question is, how do I solve this problem? I don't want to create a separate default data asset for each prefab that is going to be instantiated; furthermore, what if I'm going to be instantiating the prefab from a script? So, I'm sure there is a better way to handle this.

    Thanks in advance for your suggestions and advice!
     
  2. xucian

    xucian

    Joined:
    Mar 7, 2016
    Posts:
    756
    hey! the moment you instantiate a prefab, it doesn't have any connection to other instances or to the original prefab. only by modifying the original prefab, and only when you're in edit mode, will the instances change.
    I'm pretty sure it's something in your code that destroys all enemies at once, or at least from your description it seems like that.

    Edit: not sure what "asset" means, but if it's a ScriptableObject, for example, that might be the cause and you'll need to separately instantiate that too.
    if it's a script, maybe it has some static variables that are shared between all enemies?
     
  3. arun-muralidharan

    arun-muralidharan

    Joined:
    Jun 8, 2020
    Posts:
    3
    Thank you very much for your response!

    No, it's not the script that is killing all enemies. It is as I suspected and as you say: the asset with default data is a ScriptableObject. So, when I attach one to the prefab, all instances are using that same instance to keep track of their health, etc.

    I have "solved" the problem. Whenever I instantiate the prefab, I make a copy of the attached ScriptableObject that is specific to that prefab. Now, only the enemy that I attack dies. I don't know if this is efficient, since I have to perform a deep copy of an instance of a large class every time I instantiate the prefab. Moreover, I have to do some explicit casting during the copy because Unity/C# does not support covariant return types. But... It works for now.