Search Unity

Question Using prefab vs create gameobject via script?

Discussion in 'Editor & General Support' started by ununion, May 11, 2021.

  1. ununion

    ununion

    Joined:
    Dec 2, 2018
    Posts:
    275
    I want to know which way is better that in title?
    I have test about performance it give me same result about these two ways.

    for me if using prefab,I should manager the resources first,this is a heavy thing to do and then instantiate it.
    if using code directly,for me it is simple just init all perporty via code.
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    I don't understand the question.

    A prefab is just a pre-made hierarchy of GameObjects and components that can be instantiated.
    If you don't use prefabs, you would need to manually configure literally every GameObject and component to instantiate one "thing" in the scene, such as this, for example:
    Code (CSharp):
    1. public class EnemySpawner : MonoBehaviour {
    2.   public void SpawnEnemy() {
    3.     GameObject enemy = new GameObject("Enemy");
    4.     enemy.layer = LayerMask.NameToLayer("EnemyLayer");
    5.  
    6.     Rigidbody body = enemy.AddComponent<Rigidbody>();
    7.     body.mass = 5f;
    8.    
    9.     BoxCollider collider = enemy.AddComponent<BoxCollider>();
    10.     collider.size = new Vector3(4f, 12f, 4f);
    11.  
    12.     MeshRenderer meshRenderer = enemy.AddComponent<MeshRenderer>();
    13.     meshRenderer.mesh = GetEnemyMeshOrSomething();
    14.  
    15.     EnemyBehaviourScript script = enemy.AddComponent<EnemyBehaviourScript>();
    16.     script.health = 100f;
    17.     script.damage = 8f;
    18.     script.moveSpeed = 30f;
    19.    
    20.     //etc...
    21.   }
    22. }
    As opposed to just creating a prefab in the editor and doing this instead:
    Code (CSharp):
    1. public class EnemySpawner : MonoBehaviour {
    2.   public GameObject enemyPrefab;
    3.  
    4.   public void SpawnEnemy() {
    5.     Instantiate(enemyPrefab);
    6.   }
    7. }
    Either way, you still need to write a script to instantiate an object.

    What resources do you need to "manage" when instantiating a prefab, and how is this a "heavy" task?