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 GameObject CreateCopyFromMeshObj(string copyFromName, string objPath)
{
// Find a matching game object within the mesh object and "copy" it
// (In Unity terms, the Instantiated object is a copy)
UnityEngine.Object[] objects = AssetDatabase.LoadAllAssetsAtPath(objPath);
foreach (var obj in objects)
{
if (obj.name != copyFromName)
continue;
// We have a match but is it a game object?
GameObject gameObj = GameObject.Instantiate(obj) as GameObject;
if (gameObj == null)
continue;
// Reset the name so it is not decorated by the Instantiate call
gameObj.name = obj.name;
return gameObj;
}
// If we're here then there's an error with the mesh name
Debug.LogError(String.Format("No mesh named '{0}' to copy from.", copyFromName));
return null;
}
{
// Find a matching game object within the mesh object and "copy" it
// (In Unity terms, the Instantiated object is a copy)
UnityEngine.Object[] objects = AssetDatabase.LoadAllAssetsAtPath(objPath);
foreach (var obj in objects)
{
if (obj.name != copyFromName)
continue;
// We have a match but is it a game object?
GameObject gameObj = GameObject.Instantiate(obj) as GameObject;
if (gameObj == null)
continue;
// Reset the name so it is not decorated by the Instantiate call
gameObj.name = obj.name;
return gameObj;
}
// If we're here then there's an error with the mesh name
Debug.LogError(String.Format("No mesh named '{0}' to copy from.", copyFromName));
return null;
}