Template C# Script for Unity

[Header(“Prefabs mapping to each type:”)]
[FormerlySerializedAs(“prefabs”)]

Update 20181107:
I’ve included additional scripts to replace text in the default template.
See the BigOverview Info doc and search for >>Erweiterung<< In the Scripts DB E:\00_today\2016-07-25-files\UNITY_ScriptDB_2016-07-25\scriptsDB\Unity\BGP_extensions_and_editor_modifications\


Template and placeholder post:
This is the default link in my standard C# script template. It’s planned to change the link inside the class, if there is a detailed description available online. However this is the default text and you read this lines because there was no better description and no matching url for the class you inspected.

Some Background Info:
Every time you create a new C# script in Unity a template file is loaded.
It’s possible to change the template txt file directly on you OS / in your environment – so your default values / codes / script templates are loaded instead of the Unity Standards.

On Windows – you will find the templates here…
C:\Program Files (x86)\unity\Editor\Data\Resources\ScriptTemplates

Mac: /Applications/Unity/Editor/Data/Resources/ScriptTemplates
Mac (since 5.2.1f1): /Applications/Unity/Unity.app/Contents/Resources/ScriptTemplates

The template for the standard C# Class is…
81-C# Script-NewBehaviourScript.cs.txt

Version 1 of my 2018 Template:

#region MegAgeM C# Template Header
/*
* Copyright (c) MegAgeM 2018 - @bgp
* https://www.MegAgeM.net/
*
* More Info         :   TXT or WWW https://www.megagem.net/2018/02/05/template-c-script-unity/?script=#SCRIPTNAME#
* C# Template Info  :   https://www.megagem.net/2018/02/05/template-c-script-unity/
* bgp - Internal    :   http://www.boegi.com/n2k/?p=6522
* Version           :   #SCRIPTNAME_LOWER#_20180000_0000_0
*/
#endregion
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MegAgeM {
//[RequireComponent(typeof(Rigidbody))] // PlayerScript requires the GameObject to have a Rigidbody component
[HelpURL(&quot;https://www.megagem.net/?s=#SCRIPTNAME#&quot;)]
public class #SCRIPTNAME# : MonoBehaviour {

    #region all_variables
    //TODO - CLEAN THE TEMPLATE REGION IF NOT NEEDED! It's also available here! https://www.megagem.net/2018/02/05/template-c-script-unity/
    #region template_variables
    /*
    [Header(&quot;Variables for #SCRIPTNAME#&quot;)]
    [Space]
    [SerializeField]
    private string tmpInfoPrivate = &quot;Private but editable in the Unity editor&quot;;

    [Tooltip(&quot;This is a Tooltip for the Unity Editor&quot;)]
    [Space(10)]
    [SerializeField]
    private string tmpInfoEditor = &quot;This field has a nice Tooltip in the Unity Editor&quot;;

    [HideInInspector]
    public string tmpInfoPublicButHidden = &quot;Not visible in the Unity Editor&quot;;

    public string myString;

    [TextArea] //https://docs.unity3d.com/ScriptReference/TextAreaAttribute.html
    [SerializeField]
    private string tmpInfoMultilineTextArea = &quot;This is a multiline textarea in the editor&quot;;

    [Range(0.01f,1f)]
    public float tmpRangeTemplate = 0.5f;
    [MinMaxRange(0, 2)]

    /// &amp;amp;amp;amp;amp;lt;summary&amp;amp;amp;amp;amp;gt;
    /// This XML summary is shown in Visual Studio if you place the mouse over it
    /// &amp;amp;amp;amp;amp;lt;/summary&amp;amp;amp;amp;amp;gt;
    private string tmpInfoVisualStudio;
    */

    /* Learn this in 2018
    Three times / will add the XML summary
    Write for and Tab to get a for Loop from VS
    Use the Book symbol next to standard components to find fast results
    [MinMaxRange(0, 2)]
    */
    #endregion template_variables
    #endregion all_variables

    #region all_methods
    #region template_methods
    /*
    [ContextMenu(&quot;MethodCanBeCalledFromUnityEditor&quot;)]
    private void MethodCanBeCalledFromUnityEditor(){
        Debug.Log(&quot;YES the method was called!&quot;);
    }
    private void InvokeAfterNSeconds(){
        Debug.Log(&quot;Invoke was executed...&quot;);
    }
    */
    #endregion template_methods
    #region dev_coding_help_fus
    //[Static] Reference to this script.
	private static #SCRIPTNAME# instance;

	void Awake() {
		//Check if instance already exists...
		if (instance == null){ //if not, set instance to this
			instance = this;
		}
		else if (instance != this){ //if instance already exists and it's not this:
			//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
			Debug.LogError(&quot;ERROR - FIX IT - 2 or more times the same object! &quot;);
            Debug.Break();
            //This is used for singletons and or factories - but a big mistake to use on a gameObject not ready for this... ! Only Once per GO!
            //Destroy(gameObject);
            //Sets this to not be destroyed when reloading scene
            //DontDestroyOnLoad(gameObject);
        }
	}
    /// &amp;amp;amp;amp;amp;lt;summary&amp;amp;amp;amp;amp;gt;
	/// [Static] - Returns this script #SCRIPTNAME# as reference
	/// &amp;amp;amp;amp;amp;lt;/summary&amp;amp;amp;amp;amp;gt;
	public static #SCRIPTNAME# GetInstance() {
		if(instance == null) {
			Debug.LogError(&quot;instance missing #SCRIPTNAME#&quot;);
		}
		return instance;
	}
    #endregion dev_coding_help_fus

    public void Start () {
        //if(templateVar == null){ Debug.Log(&quot;templateVar was not assigned in the Inspector - Please do or code a find method.&quot;); Debug.Break();}
        //Invoke(&quot;InvokeAfterNSeconds&quot;, 2f);
		#NOTRIM#
	}
    #endregion all_methods
  }
}

Additional Links:
Source: https://youtu.be/_g1TyAGk6Lk?list=PLPV2KyIb3jR4dNDPcSiAY-73gAKRIiPk4&t=190

Hidden content detected! Please login.

Enum and State Machines:
Search for PanelHandler.cs and use the TAB key (plus Arrow right) in VisualStudio to get perfect switch case code blocks for the State machine and other Enum related switch case things.

Folder Structure:

bgp_TEILPROJEKT
-0INFO
–readme.docx (Credits,Screenshots,Links)
–screenshot.jpg
-scripts
-scenes
-sprites
-models
-materials

Workflow “Asset Extraction” from AssetStorePackages:

In the main project (day2K) create a side folder named “construct”. In here the Asset will be downloaded and the asset needed will be extracted as UnityPackage.
In the main project (day2K) create another side folder “repackage”. In here the UnityPackage will be imported and fixed if needed.
Afterwards the package can be saved! but most important is the import to the new project.

Delegate and Events:
public delegate void ClickActionXYZ();
public static event ClickActionXYZ OnClicked;

E:\00_today\2018-03-08-files\UNITY_DelegateAndEventRecap_2018-03-08\Delegate_and_Event_Recap\Assets

Update already in the Editor?
Details see BigXlsX Knowledgebase and there the “Update Already in the Editor?!” Caption.

[ExecuteInEditMode()]
public virtual void Update() {

Menuitems and other Things for the Unity Editor:
MenuItems und andere Sachen für den Editor: Extract from https://unity3d.com/es/learn/tutorials/topics/tips/unity-tips-tricks-3

1)
using UnityEditor;

In the inspector – add a button to a stringfield. (Reset to default values for example)
Im Inspektor – ein Button auf dem Feld z.B. um DefaultWerte widerherzustellen:
[ContextMenuItem(“Set my string”, “SetString”)]
public string myString;

ContextMenu:
[ContextMenuItem(“Set my string”, “SetString”)]
public string myString;

Ranges:
[Range(2, 5)]
public float myFloat;

[ContextMenu(“Item added to Context Menu”)]
void TestContextMenu() {
Debug.Log(“Context Menu”);
}

[MenuItem(“CONTEXT/Rigidbody/Double Mass”)]
static void DoubleMass(MenuCommand command) {
Rigidbody rb = (Rigidbody)command.context;
rb.mass = rb.mass * 2;
}

[MenuItem(“Tools/3D/Set Mass”)]
static void SetMass() {

Update:
Add Pragma Info to get rid of some ErrorMessages 😉
https://answers.unity.com/questions/21796/disable-warning-messages.html

Some values in the current code (see at top – did not work) / They are from a tutorial on ScriptableObjects and only valid with the other settings from this tutorial!

TODO – CodeComment for the GetInstance
Add [AddComponentMenu(“SpacePuppy/Spawn/Spawn Pool”)]
Singleton Multiton discussion…
https://forum.unity.com/threads/singletons-is-it-bad-practice.292655/

UPDATE –
NEXT VERSION – PLEAS READ THROUGH and ADD ________________

Improving the Unity Editor Inspector with Unity Attributes

7 Ways to Make Your Unity Components More User-Friendly


http://blog.theknightsofunity.com/use-decorator-drawers-improve-inspector-view-scripts/
https://docs.unity3d.com/ScriptReference/PropertyDrawer.html
https://docs.unity3d.com/ScriptReference/DecoratorDrawer.html

https://unity3d.com/de/learn/tutorials/topics/interface-essentials/building-custom-inspector