Copying and Pasting cs Code

In cs, like in almost any computer programming language, reading data from a file can be tricky. You add extra lines of code to tell the computer what to do. Sometimes you can copy and paste these lines from other peoples’ code.

For example, you can follow the pattern in this listing:

         private void CreatePrefab(XElement xmlPrefab, string objPath)
         {
             var customImporters = GetCustomImporterInstances();

             // Part 1: Create the prefab
             string prefabName = xmlPrefab.Attribute("name").Value;
             float prefabScale = ImportUtils.GetAttributeAsFloat(xmlPrefab, "scale", 1.0f);
             GameObject tempPrefab = new GameObject(prefabName);
             HandleCustomProperties(tempPrefab, xmlPrefab, customImporters);

             // Part 2: Build out the prefab
             AddGameObjectsTo(tempPrefab, xmlPrefab, objPath, customImporters);

             // Part 3: Allow for customization from other editor scripts to be made on the prefab
             // (These are generally for game-specific needs)
             CustomizePrefab(tempPrefab, customImporters);

             // Part 3.5: Apply the scale only after all children have been added
             tempPrefab.transform.localScale = new Vector3(prefabScale, prefabScale, prefabScale);

             // Part 4: Save the prefab, keeping references intact.
             string prefabPath = ImportUtils.GetPrefabPath(prefabName);
             UnityEngine.Object finalPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));

             if (finalPrefab == null)
             {
                 // The prefab needs to be created
                 ImportUtils.ReadyToWrite(prefabPath);
                 finalPrefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
             }

             // Replace the prefab, keeping connections based on name.
             PrefabUtility.ReplacePrefab(tempPrefab, finalPrefab, ReplacePrefabOptions.ReplaceNameBased);

             // Destroy the instance from the current scene hiearchy.
             UnityEngine.Object.DestroyImmediate(tempPrefab);
         }