Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Last active June 25, 2021 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtdekker/5dbd1d30890c3905adddf4e7ba2b8580 to your computer and use it in GitHub Desktop.
Save kurtdekker/5dbd1d30890c3905adddf4e7ba2b8580 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyScript : MonoBehaviour
{
// Always call this to create MyScript objects so we know they are complete.
// Never use AddComponent<MyScript>() outside of this class.
public static MyScript Create(
string resourcesPath,
string additionalArgument1,
int otherArgument
// add more "must have" arguments here, assign them below
// to either the newly-created or newly-instantiated object.
)
{
// NOTE: only have ONE of the following two blocks of code, not both:
// Option 1:
// code for if this is a pre-defined prefab that you're going
// to load, instantiate, and then customize a bit.
// You can also keep its source path private to this class.
GameObject prefab = Resources.Load<GameObject>( resourcesPath);
GameObject go = Instantiate<GameObject>( prefab);
MyScript myScript = go.GetComponent<MyScript>();
// Option 2:
// code for making a new GameObject from scratch
//MyScript myScript = new GameObject( "MyScript.Create();").
// AddComponent<MyScript>();
// jam in the arguments we need (remember, Awake has already executed!!)
myScript.additionalArgument1 = additionalArgument1;
myScript.otherArgument = otherArgument;
return myScript;
}
string additionalArgument1;
int otherArgument;
void Start()
{
/// etc...
}
void Update()
{
/// etc...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment