Guest User

Unity factory pattern, treating AddComponent as though it were private

a guest
Aug 14th, 2020
1,202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class MyScript : MonoBehaviour
  6. {
  7.     // Always call this to create MyScript objects so we know they are complete.
  8.     public    static    MyScript    Create(
  9.         string resourcesPath,
  10.         string additionalArgument1,
  11.         int otherArgument)
  12.     {
  13.         // NOTE: only have ONE of the following two blocks of code, not both:
  14.  
  15.         // Option 1:
  16.         // code for if this is a pre-defined prefab that you're going
  17.         // to load, instantiate, and then customize a bit.
  18.         // You can also keep its source path private to this class.
  19.         GameObject go = Resources.Load<GameObject>( resourcesPath);
  20.         go = Instantiate<GameObject>( go);
  21.         MyScript myScript = go.GetComponent<MyScript>();
  22.  
  23.         // Option 2:
  24.         // code for making a new GameObject from scratch
  25.         //MyScript myScript = new GameObject( "MyScript.Create();").
  26.         //    AddComponent<MyScript>();
  27.  
  28.         // jam in the arguments we need (remember, Awake has already executed!!)
  29.         myScript.additionalArgument1 = additionalArgument1;
  30.         myScript.otherArgument = otherArgument;
  31.  
  32.         return myScript;
  33.     }
  34.  
  35.     string additionalArgument1;
  36.     int otherArgument;
  37.  
  38.     void Start()
  39.     {
  40.         /// etc...
  41.     }
  42.  
  43.     void Update()
  44.     {
  45.         /// etc...
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment