How should i create & add components to a gameobject in a loop?

Hello,
I’m trying to add some more functionality to a script and im confused on how to use instantiate. I have an OnEntityCreated callback and a switch statement, and i need to create a gameobject & give it some components depending on what part of the switch statement it went to. Do i need to create a prefab and use that or should i create an empty gameobject and add the components like that? thanks

void OnEntityCreated(BSPLoader.EntityInstance instance, List<BSPLoader.EntityInstance> targets) {
            Debug.Log("Creating \"" + instance.entity.ClassName + "\" at \"" + instance.entity.Origin + "\" raw obj: " + instance.entity);
            //GameObject model = FindModel(instance.entity.Model);
            GameObject model = AssetDatabase.LoadAssetAtPath<GameObject>(instance.entity.Model);
            model = AssetDatabase.LoadAssetAtPath<GameObject>(instance.entity.Model);
            Instantiate(model, instance.entity.Origin, Quaternion.identity);
            switch (instance.entity.ClassName)
            {
                case "func_door":
                   
                    break;
                case "func_button":
                   
                    break;
                case "ambient_generic":
                   
                    break;
                case "prop_physics":
                  
                    break;
                case "prop_dynamic":
                   
                    break;
                case "npc_security_camera":

                   
                    break;
                case "func_light":
                   
                    break;
                case "default":
                    Debug.LogWarning("No matches for " + instance.entity.ClassName + " in the switch statement");
                    break;
            }
          
    }

Instantiate returns the object that was created, so use that. AddComponent also returns the component you just added, so you can set values to it.

GameObject instance = Instantiate(model, instance.entity.Origin, Quaternion.identity);

// for example:
switch (instance.entity.ClassName)
{
   case "func_light":
       Light light = instance.AddComponent<Light>();
       light.intensity = // however you're reading the value from the file
                   
       break;
}

You might be a little in over your head though trying to mod / re-create another game or whatever you’re doing here exactly.

1 Like