Search Unity

Differentiate Instance from Original prefab

Discussion in 'Prefabs' started by MGGDev, Feb 4, 2019.

  1. MGGDev

    MGGDev

    Joined:
    Nov 6, 2018
    Posts:
    27
    Hello,

    I am trying to give each prefab instance a specific ID in one its scripts during OnValidate(), but it triggers while editing the original prefab. Is there a way (in C#) to know whether this gameObject is a prefab instance or the main prefab?

    Thanks.
     
    idbrii likes this.
  2. pod11

    pod11

    Joined:
    Jan 6, 2019
    Posts:
    60
    Sorry for bargin in, but im trying to figure out something that might be related to your question.
    I want to make spawners ( instantiated from prefabs) spawning enemies( also from prefabs), and when enemy gets killed i want it to give feedback to specific spawner it was created in- so it knows to start spawning new monster.

    How ho send information to specific instance of object created from prefabs?
    I've been trying to find answer, but im begginer, and don't know proper nomenclature of what im looking for, i'd appreaciate a tip.
     
  3. MGGDev

    MGGDev

    Joined:
    Nov 6, 2018
    Posts:
    27
    No problem :)
    The first tip is that it is almost always better to make a new topic for your question, because right now, your question will only be seen by a few people (only those who open this topic).
    You can also try Unity Answers for better (and probably faster!) response.
    Second, try to explain more details in your new topic, like the hierarchy of your objects, some script logic about how your instantiation code works ..etc.

    Good luck!
     
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,332
    You'll want to check if the Prefab Stage is open, using PrefabStageUtility, and then skip the edit if that's the case.

    What you really want to check is if you're looking at a prefab asset rather than a prefab instance, but when you're in the prefab view, looking at the prefab itself, the API tells you that it's not a prefab due to really leaky abstractions. A generally safe rule is that if the prefab stage is open, you don't want to edit your GUIDS, as they're either on the prefab, or on a nested prefab, and in either case you don't want to do the edit.
     
    idbrii and MGGDev like this.
  5. MGGDev

    MGGDev

    Joined:
    Nov 6, 2018
    Posts:
    27
    Thank you!
    For anyone curious, this is how the check works:
    (Edit: Add activeInHierarchy check, to prevent adding the prefab itself)
    Code (CSharp):
    1. if (PrefabStageUtility.GetCurrentPrefabStage() == null && gameObject.activeInHierarchy)
    2.        Debug.Log("This is a prefab instance.");
     
    Last edited: Feb 7, 2019