Unity C# Tips Generated via GPT-3

These tips may be right, these tips may be wrong, but they're all auto-generated by an AI. Something to read on the train, in bed or wherever you like! Please verify tips you find interesting by doing independent research on whether they're really reasonable, or just use them as inspiration for topics, functions and keywords to look more into.
Philipp, 2022-10-28


#Tip 1.

Try to avoid using too many nested if-else statements in your code. A cleaner and more readable alternative is to use the conditional operator (? :) like this:

bool condition = true;

string result = condition ? "Yes" : "No";


#Tip 2.

If a method returns a boolean value, you can immediately return if the method returns false . For example, if you have a method that performs some validation, you can do this:

bool Validate() { if (!DoValidation()) { return false; } // more code goes here... }


#Tip 3.

If you want to create a realistic water effect, you can use a shader. Shaders can create wonderful effects like ripples or waves on the surface of your water.


#Tip 4.

If you have a list of objects, and you want to get a list of distinct objects based on a property of those objects, you can use the LINQ Distinct operator.


#Tip 5.

If you want to make a gameObject move towards another gameObject, you can use the "Look At" function.

To do this, simply select the gameObject you wish to move, then click on "Component > Scripts > Add Component > New Script".

Name the script something like "LookAtTarget".

In the script, you will need to make a reference to the gameObject you wish to move towards (the target).

You can do


#Tip 6.


<placemark>
    <gx:balloonVisibility>0</gx:balloonVisibility>
    <coordinates>-147.3067,59.7848,276.292</coordinates>
</placemark>


This is sample XML encoded data in the


#Tip 7.

If you want to improve your performance in Unity 3D, consider using the profiler. The profiler can help you identify areas where your game is spending too much time, and show you ways to optimize your code.


#Tip 8.

If a method or property (I'm including properties on my definition of method) returns a non-primitive type, the type should be immutable. If you make it immutable, you will save your users (yourself and other developers) a lot of bug fixing pain.
Added to that, if your method is returning an IEnumerable, then it should be an IEnumerable<T> of some immutable type T, so that unwanted changes to that collection cannot potentially wreak havoc elsewhere


#Tip 9.

When creating gameobjects, many are created by calling gameObject.Instantiate.  When you do this, instead of creating the gameObject like this:

var gameObj = new GameObject();


Do this:

var gameObj = GameObject.CreatePrimitive();


This way you don't have to worry about setting the object's mesh and material.


#Tip 10.

https://www.youtube.com/watch?v=qx3fgDmmGuU


#Tip 11.

When working with the System.String class in C#, it is often useful to use the String.Format() method. This method allows you to specify a format string which contains placeholders for the values that you want to insert into the string. For example, if you want to insert a person's first and last name into a string, you can use the following format string:

"{0} {1}"

where {0} will be replaced by the first


#Tip 12.

If you have a MonoBehaviour-derived class that needs to do some work in Update, but you only want that work done once per frame, cache a reference to the current frame number in a private field at the start of Update, and check it before doing the work. Like this:

private int currentFrame;

void Update()

{

if (currentFrame != Time.frameCount)

{

currentFrame = Time.frameCount


#Tip 13.

If you need to format a string in C#, you can use the String.Format method. This method takes a format string and an array of objects, and returns a formatted string. For example, you could use it like this:

string s = String.Format("The answer is {0}", 42);

This would result in the string "The answer is 42".


#Tip 14.

If you want to create a handy shortcut for a Vector3, you can create a static class with a static member like this:

public static class Vector3Extensions { public static Vector3 One = new Vector3(1, 1, 1); }

And then you can use it like this:

Vector3 myVector = Vector3Extensions.One * 2;

This is a really quick and easy way to create a Vector3 with the value


#Tip 15.

If you want to create a realistic water effect, try adding aScripts/DisableEyeAdaption to your scene. This will disable the bloom effect and make the water look more realistic.


#Tip 16.

If you want to change the color of an object over time, you can use the Lerp function. To use this, you first need to create two variables, one for the starting color and one for the ending color. Then, you can use the Lerp function to interpolate between the two colors over time.


#Tip 17.

If you create a method called CreateUser, it may make sense to also
create methods called GetUser, UpdateUser, and DeleteUser.


#Tip 18.

We frequently need to iterate through our child gameobjects, usually to find all objects with a certain component or tag, for a number of reasons.
Instead of writing this repetitive code over and over again:

var renderers = GetComponentsInChildren<Renderer>();
foreach (var rend in renderers)
{
    rend.material.color = Color.red;
}


You can create a reusable


#Tip 19.

If you're using a lot of objects of the same type, consider using a
collection instead.


#Tip 20.

private bool _isChanged = false;
public bool IsChanged
{
   get { return _isChanged; }
   set
   {
      _isChanged = value;
      OnPropertyChanged("IsChanged");
   }
}

This pattern provides a concise way to track whether a property has been changed, and also raises the PropertyChanged event automatically.


#Tip 21.

You can use the Debug.Log() method to write messages to the console. This can be helpful for debugging purposes or for displaying information to the user.


#Tip 22.

To rotate a game object according to a certain speed, you can use this code:

transform.Rotate(Vector3.up * Time.deltaTime * rotateSpeed);


#Tip 23.

To convert a string to a byte array, you can use the System.Text.Encoding.ASCII.GetBytes method.


#Tip 24.

If you want to create a smooth camera movement, use the Transform.Lerp() method. This will interpolate between two Transform objects over time, creating a smooth movement.


#Tip 25.

If you want to create a glass material, make sure to use a shader that supports transparency. To do this, go to the Shader dropdown in the Material Inspector and select one of the Transparent shaders.

In the Main Texture field, select the texture you want to use for the glass. This should be a transparent texture with a smooth alpha gradient.

Next, set the Color field to white. This will make the glass appear more opaque.

Finally


#Tip 26.

If you want to spawn a new object at a random position within a given range, you can use the UnityEngine.Random.Range(float min, float max) method.


#Tip 27.

If your code is getting too messy and hard to read, try breaking it up into smaller chunks by creating new functions. This will make your code more organized and easier to read.


#Tip 28.

If you need to invoke a delegate, but you don't have a reference to a specific object, you can use the built-in System.Action delegate.

Here's an example:

public class MyClass { public void MyMethod() { // Do something here } } public class MyOtherClass { public void MyOtherMethod() { // Invoke the MyClass.MyMethod delegate Action myDelegate = new Action(MyClass.MyMethod); myDelegate


#Tip 29.

If you need to do something repeatedly at a fixed interval, you can use the InvokeRepeating() method. This method takes two parameters:

- The name of the method to call
- The time interval (in seconds) between calls

For example, if you need to call the MyMethod() method every 5 seconds, you would use the following code:

InvokeRepeating("MyMethod", 0, 5);


#Tip 30.

If you have a Unity C# script that needs to do something on a regular basis, you can use the InvokeRepeating() method to call a method at regular intervals. For example, if you wanted to call a method every second, you could use the following code:

void Start () { InvokeRepeating ("MyMethod", 0.0f, 1.0f); } void MyMethod () { // Do something here }


#Tip 31.

In Unity 3D, you can create a black hole effect by using a Black Hole script.


#Tip 32.

For example, if you wanted to output "Hello World" in C#, you would use the following code:

Console.WriteLine("Hello World");


#Tip 33.

If you want to convert a string to a byte array, you can use the Encoding.UTF8.GetBytes method.


#Tip 34.

If you want to see what is being printed in the Output (debug) Sytem.Log keep this console command added to the  Unity C# file you are working on:

using UnityEngine.SceneManagement;
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEditor;

public class ConsoleTest : MonoBehaviour
{
    public static string consoleFile = "";
    StreamWriter writer =


#Tip 35.

When you want to invoke a method on a type, but you're not sure if the type actually supports the method, use the "dynamic" keyword. For example:

var myObject = GetMyObject();

dynamic myDynamicObject = myObject;

myDynamicObject.DoSomething();

This will invoke the DoSomething() method on myObject, if it supports it. If not, it will throw an exception.


#Tip 36.

If you need to count the number of objects in a scene, you can use the static member UnityEngine.Object.FindObjectsOfType. This member returns an array of all active and enabled objects of the specified type in the scene.


#Tip 37.

§§ \dfrac{f(n)}{g(x)} = n ^{x-1} $$

In C# Linq, you can use the following code to compute the above expression:

var result = f.Select(n => Math.Pow(n, x - 1)).Zip(g, (a, b) => a / b);


#Tip 38.

If you want to create a realistic water effect, make sure to use a shader that supports refraction and transparency. You can find some great shaders on the Unity Asset Store, or you can create your own.


#Tip 39.

In Unity, it is often useful to have a base class from which other classes can inherit. This base class can contain fields and methods that are common to all of the child classes. For example, a base class for a character in a game could contain fields for the character's health and damage, and methods for attacking and taking damage.


#Tip 40.

<br>

Use the GetComponent method to get a reference to a component attached to a GameObject. For example, if you have a script attached to a GameObject and you want to get a reference to the SpriteRenderer component, you can do so like this:

SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();


#Tip 41.

If you want to add a component to an object, you can use the AddComponent() method. For example, if you want to add a Rigidbody component to an object, you can use the following code:

object.AddComponent<Rigidbody>();


#Tip 42.

When working with the System.IO namespace, it is often useful to use the Path class to manipulate file and directory path strings. The Path class provides a number of static methods that can be used to perform operations on strings that contain file or directory paths.

For example, the GetDirectoryName() method can be used to retrieve the directory name from a path string:

string path = @"c:\temp\MyFile.txt";

string dir = Path.


#Tip 43.


using System.Collections.Generic;
using System.Linq;
public class MyClass
{
  public List<int> myInts = new List<int>(){1, 2, 4, 9};

  public List<int> GetIntsInInterval(int min, int max)
  {
     return myInts.Where(g =&gt


#Tip 44.

anonymous delegates. Basically you can create an anonymous deleate (a method without a name) by using the delegate keyword and assigning it to a variable.



Here's an example:

delegate void MyDelegate();

MyDelegate del = delegate { Console.WriteLine("Hello, world!"); };

del(); // Prints "Hello, world!"


#Tip 45.

If you want to print a message to the console, you can use the Debug.Log() function. For example,

Debug.Log("This is my message");

will print "This is my message" to the console.


#Tip 46.

Never return null from a public method. Instead, return an empty collection or an empty string. This will prevent your code from having to check for null values all the time.


#Tip 47.

If you want to create a smooth camera follow in Unity, you can use the Vector3.Lerp() method.


#Tip 48.

If you want to quickly add a lot of objects to your scene, you can use the " Duplicate " function in the " Edit " menu. This will create an exact copy of the object you have selected.


#Tip 49.

If you're trying to create a mesh in Unity, you can use the Mesh class. To create a mesh, you need to specify a set of vertices and indices. The vertices specify the positions of the mesh, and the indices specify how the vertices are connected.


#Tip 50.

you can use the [NotImplementedException](https://docs.microsoft.com/en-us/dotnet/api/system.notimplementedexception?view=netcore-3.1) when you want a method to eventually do something but haven't implemented it yet.

For example,


csharp
public class MyClass
{
    public void MyMethod()
    {
        throw new NotImplementedException();


#Tip 51.

If you want to quickly generate boilerplate code for an event handler method,
i.e. a method that has a signature matching a delegate type, put your caret inside the
delegate type name, hit
<C-k>
, then start typing the name of the method you want to
create. After you type the method's name and hit space, you'll be prompted to insert a
variable name. Once you type that


#Tip 52.

If you need to perform an operation on each element in an array, you can use the foreach loop. This loop will execute the given operation on each element in the array, one at a time.


#Tip 53.

If you want to create a quick and dirty prototype, you can use the Unity 3D asset store. It has a lot of free and paid assets that can help you save time and get your prototype up and running quickly.


#Tip 54.

If you need to create a new instance of a class, you can use the "new" keyword. For example:

Class1 myClass1 = new Class1();


#Tip 55.

Don't use numeric literals in your code. Instead, create constants or fields for them. That way, if you ever need to change the value of the literal, you can do so in one place, and you won't have to go hunting through your code for all the places where you used that literal.

Here's an example:

Instead of this:

public void DoSomething()
{
    const int maxRetries = 3;


#Tip 56.

when writing methods that take a single list of objects, consider using IEnumerable. Although the IEnumerable interface is not as well known as IList, it actually has many advantages, 1.) IEnumerable structures can be effortlessly transformed into other, more compact structures without allocations, 2.) no needless boxing and unboxing during simply iteration and subscription, and 3.) allows for easy thread-safety in iterator blocks.

Here is a concrete example:

public static IEnumerable<


#Tip 57.

seldom write

same code twice

.


#Tip 58.

Use the String.Format method to improve the readability of your code. This method allows you to insert values into a string template, making it much easier to see what your code is doing.

For example, consider the following code:

string name = "John";

int age = 20;

Console.WriteLine("Hello, my name is {0} and I am {1} years old.", name, age);

This code will output


#Tip 59.

If you want to create a new object, it is usually best to use the "object initializer" syntax, like this:

var newObj = new MyClass()
{
    Property1 = "Hello",
    Property2 = "World"
};


#Tip 60.

If your code is executing a method on an object and then immediately checking a property or field on that same object, it is usually more efficient to combine the two operations into a single method call. For example, instead of this:

string s = obj.SomeMethod();

if (s != null)

{

// do something with 's'

}

You can do this:

if (obj.SomeMethod() != null)


#Tip 61.

If you want to create a new object in Unity and have it appear in the scene, you can use the Instantiate() method. For example, if you wanted to create a new cube, you could use the following code:

GameObject cube = Instantiate(Resources.Load("Prefabs/Cube") as GameObject);

This would create a new GameObject, load the prefab for a Cube from the Resources folder, and assign it to the newly created Game


#Tip 62.

You can use the
SendMessage
method (docs here) to execute a method on another object.
To do this from code, you'll need a reference to the object you want to call the method on - this can be retrieved in a number of ways, including looking it up by tag or name, storing it in a variable, or passing it in as a parameter to the method.
Here's some example code that calls the
DoSomething</


#Tip 63.

If you need an object to rotate around another object, you can use the
RotateAround
function. For example, if you want an object to rotate around the Z axis, you would use:

transform.RotateAround(transform.position, Vector3.forward, Time.deltaTime * speed);


#Tip 64.

If you want to get the current position of the mouse in world space, you can use the following code:

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);


#Tip 65.

If you want to create a more realistic lighting effect in your scene, you can use light maps. Light maps are textures that store information about how light interacts with surfaces in your scene. To create a light map, you first need to bake the lighting information into a texture using the Lightmap Settings panel. Once you have baked the lighting information, you can apply it to your surfaces using the Lightmap Settings panel.


#Tip 66.

If you root node X contains n child nodes, you can use a for loop to iterate through the nodes in your XML like so:

// root is your XML root node
foreach (XElement child in root.Descendants("child"))
{
    Console.WriteLine(child.Name);
}
// This outputs "child" n times, where n is the number of children of root.


#Tip 67.

Imagine that you have a list of items that you need to perform an action on, such as list of files in a directory. If you need to perform an action on each step of the loop, you can leverage LINQ's Select() method to create a new anonymous type that has the results of an action or memoization. (In other words, store the result of each loop's iteration in a new field in the assembly.)

// list of files in a directory var filesInDir


#Tip 68.

If you find yourself frequently needing to call a Unity function from a C# script, such as SendMessage or GetComponent, it may be worth creating a static class with extension methods for these functions. That way, you can call the functions using the syntax MyClass.MyFunction() instead of having to use the full Unity syntax MyGameObject.SendMessage("MyFunction").

This can help to make your code more readable and maintainable.


#Tip 69.

Use UnityEvent events to avoid boilerplate code when working with code that's triggered by events like button presses. This can reduce the code a programmer has to write and make code more understandable and easier to work with.

To use an UnityEvent, add a using UnityEngine.Events; line at the top of your script, then declare a public UnityEvent variable. In the Unity Editor, you can then drag and drop objects into the Event Horizon field to have them listen for the event.


#Tip 70.

If you're having trouble with jagged edges on your models, you can try using the Smooth Vertex tool. Select your model in the Hierarchy, then go to Mesh > Smooth Vertex in the top menu. This will smooth out the edges of your models and make them look nicer.


#Tip 71.

When using the "using" keyword to create a new object, always specify the type of object you are creating.

For example:

using (MyClass myClass = new MyClass())

{

...

}


#Tip 72.

When you need
  an assignment that keeps the value of an existing variable, but
  modifies it slightly, keep in mind that you can use the increment and
  decrement operators (
++
and
--
).

For example, say you want to keep the value of
x
but add 1 to it. You could write:


x = x + 1;


#Tip 73.

If you want to iterate over a collection, you can use the foreach loop.


#Tip 74.

You can create a new
Task
in C# like this:

new Task( () => Console.WriteLine("Hello world!") );


#Tip 75.

when you need to return multiple values from a method and you're using a tuple to do this (e.g. ` Method() => (int result, string message);`), return `null` instead of the tuple when the method fails.

This way, you can use the null coalescing operator (`??`) to handle the error case:


csharp
var (result, message) = Method();
if (result == null)
{


#Tip 76.

If you want to create a new object, you can use the "GameObject.CreatePrimitive" method. This will create a new object with a default mesh and collider.


#Tip 77.


#Tip 78.

Spawning a new object in Unity 3D is easy! All you need to do is use the Instantiate() method. This method takes in a GameObject as a parameter and will spawn a new instance of that object in the scene.


#Tip 79.

A lot of the time you want to show different information to the player depending on whether an object is active or inactive.  A common way to do this is to use the gameobject.activeSelf property, like this:

if (gameobject.activeSelf)
   {
   // do something
   }
else
   {
   // do something else
   }


However, this can be a bit inefficient because it requires two


#Tip 80.

change the top speeds for each of your player's locomotion animation states. In the following example, we change the speeds for walk and run animations to 0.8 and 1.2, respectively.


cs
// gets the animator component attached to the player
Animator animator = GetComponent<Animator>();

// gets the info for the walk state
AnimatorStateInfo walkState = animator.GetCurrentAnimatorStateInfo(0);


#Tip 81.

If you want to create a prefab out of a game object, you can drag the game object into the "Project" area in the Unity editor.


#Tip 82.

Edit
<blockquote>
<p>Be sure to import the System.Linq namespace for LINQ extension
  methods.</p>
</blockquote>
Here's an example of how you can use LINQ to pad a string:

var text = " example ";
text = text.Trim();
int numberOfPads = 5 - text.Length / 2;
text = new string(' ', 5) + text.Pad


#Tip 83.

You can use the "as" operator to safely cast a type to another type. For example, you can cast a List<string> to an IEnumerable<string>.


#Tip 84.

If you want to create a more realistic environment, try using some of the shaders that are available. There are shaders that can simulate different kinds of surfaces, such as metal or glass, and they can make your scene look more realistic.


#Tip 85.

In Unity, you can create prefabs of common objects or groups of objects. This can save you a lot of time when you need to instantiate similar objects in your scene.


#Tip 86.

if you're using LINQ say on a List<A>, where A is some class, you often have to pass in statements where code uses an object of type A. You can't just pass in a method name (or an anonymous delegate), but have to have an object of type A as well.
My question is: what's the best way to pass this into a method, and how would you write that information in the proverbial C# book (i.e., what's the


#Tip 87.

If you want to create a realistic water effect, make sure to use a shader that supports translucency. For example, the StandardShader in Unity 3D supports translucency, so you can use that to create a realistic water effect.


#Tip 88.

Assuming a base class named "Base" and a sub class named 'Sub'

There are cases when you need some code in both the 'Base' and 'Sub'CLASS to call the same piece of code. Since 'Sub' derives from 'Base' you can create a method in the 'Base' file that the 'Sub' class can inherit simply by overriding it. However if the 'Base' class doesn't need you to override then you could make it just like a


#Tip 89.

If you need to find out if a certain key is being pressed, you can use the Input.GetKey() function. For example, if you need to find out if the "a" key is being pressed, you can use the following code:

if (Input.GetKey("a"))
{
    // Do something
}


#Tip 90.

If you need to move an object around in 3D space, you can use the Transform component. To access the Transform component, select the object in the Hierarchy panel and then look for the Transform component in the Inspector panel.

To move the object, you can use the position, rotation, and scale properties. For example, to move an object to the right, you would use the position property and set the x value to 1.


#Tip 91.

You can create a portal in Unity 3D by using the Portal prefab.


#Tip 92.

_myAction?.Invoke();

This will safely invoke the action only if it is not null.


#Tip 93.

To create a multiline string in C#, you can use the @ symbol before the string literal. For example:

string myString = @"This is a

multiline

string";


#Tip 94.

If you want to check if a string contains a certain substring, you can use the Contains() method. For example:

string myString = "Hello world";

if (myString.Contains("world"))

{

// do something

}


#Tip 95.

<blockquote>
<p>Pick up the hacky programming style first, until you realise how much
  easier general and flexible programming practices will make your life.
  For example improve on loop code until it becomes more like:</p>
<pre>
<code>    for (var item in whateverList) {
</code>
</pre>
<p>...rather than traditional (


#Tip 96.

When you have a list of variables that you want to track, don't store them in the fields of their parent class. Create a seperate class that contains all the items you want to track. Then keep a single instance of that class available in your parent script as a field. Make that field publicly available as a property.



Here's an example. Let's say you have a Player class in Unity, and you want to track the player's health, mana, and stamina.


#Tip 97.

If you want to obtain the results of a LINQ query as a List<T> instead of an IEnumerable<T>, you can use the ToList() extension method. For example:

var results = from n in numbers
              where n % 2 == 0
              select n;

List<int> evenNumbers = results.ToList();


#Tip 98.

If you're working with a lot of data, it's often helpful to create a custom data structure to hold that data. For example, if you're working with a lot of employee data, you might create a custom Employee class to hold that data.

Creating a custom data structure can make your code more readable and easier to debug. It can also help you optimize your code for performance.


#Tip 99.

If you want to convert a type to another type, you can use the Convert class.

For example, if you want to convert an int to a string, you can use the following code:

string s = Convert.ToString(5);


#Tip 100.

When working with the using keyword, it is considered best practice to declare and instantiate your objects within the using block. This ensures that the object is properly disposed of when no longer needed.

For example:

using (var myObject = new MyObject()) { // Use myObject here }


#Tip 101.

If you need to generate a random number in C#, you can use the System.Random class.


#Tip 102.

add methods to the collection properties you send from your user controls to the ViewModel that retrieve the selected values from the collection.  So perhaps your ViewModel has:

private List<Product> _availableProducts;
public List<SelectListItems> AvailableProducts
{
    get { return _availableProducts.Select(p => new SelectListItem { Text = p.Name, Value = p.Id.To


#Tip 103.

always do testing in the editor when starting new components

This will help you catch any errors or unexpected behaviour as you are building your component. It is also a good way to ensure that your component is functioning as expected before you build it for your final project.


#Tip 104.

How To Build A Singleton:

    public class Singleton
    {
        private static readonly Singleton instance = new Singleton();
    
        static Singleton()
        {
        }
    
        private Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                return instance;
            }
        }
    }


#Tip 105.

// Assets folder inside an MonoBehavior .cs file
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class Example : MonoBehaviour {
    // Use this for initialization
    void Start ()
    {
        String folder = "Assets";
        String path = Application.dataPath + "/" + folder
        DirectoryInfo dir = new DirectoryInfo(path);


#Tip 106.

One tip for Unity 3D is to use the layer system to your advantage. By default, Unity will put everything on the "Default" layer. However, you can create your own layers and assign objects to them. This can be useful for organization and can also help with performance. For example, if you have a lot of objects on the "Default" layer, your game may run slowly. However, if you put some of those objects on a different layer, it may run faster


#Tip 107.

The System.IO.Ports.SerialPort class allows you to communicate with a serial port. The following code opens a serial port, sends a string to it, and then reads the response:

using System.IO.Ports;

SerialPort port = new SerialPort("COM4", 9600);
port.Open();
port.WriteLine("Hello world");
string response = port.ReadLine();
port.Close();


#Tip 108.

If you need to perform an operation on a large number of items in an array, you can use the System.Array.ForEach method. This method allows you to specify a delegate that will be called for each item in the array. The delegate can perform any operation you need, making this a very powerful way to manipulate arrays.


#Tip 109.

You can use the String.Format() method to insert variables into a string. For example, if you have a string "The answer is {0}" and a variable answer with the value 42, you can use String.Format() to print "The answer is 42".


#Tip 110.

If you need to access the position of an object in 3D space, you can use the Transform.position property. This will give you the object's position as a Vector3, which you can then use for whatever purpose you need.


#Tip 111.

If you're working with a lot of data, it can be helpful to use the StringBuilder class instead of the String class. StringBuilder is designed for efficiently concatenating strings, whereas String is not.


#Tip 112.

Don't let values (eg integers, floats, strings, arrays and any other value types) drift away from their hubs.

For example, an integer might have a "current value" and a "desired value". The desired value is where you want the integer to be (maybe it's the player's health, and the desired value is 100). But the current value is where the integer actually is at the moment - which might be anything from 0 to 100.

The point


#Tip 113.

If you have a target object that you want another object to follow, you can use the "Look At" feature. With the target object selected, go to the "Component" menu and choose "Add Component->Camera->Camera (cript). This will add the "Look At" script to the target object. Then, with the new script selected, go to the "Inspector" panel and drag the object you want to follow into the "Target" field.


#Tip 114.

Use the [SerializeField] attribute to make public variables visible and editable in the Unity Inspector, but not directly accessible from code. This is useful for making variables that you want to be able to tweak in the Inspector, but that you don't want other parts of your code to be able to change directly.


#Tip 115.

In the scene view, you can hold
Alt
and drag the mouse to rotate the view.


#Tip 116.

If you want to create a custom cursor for your game, you can create a Canvas UI object and then add an Image component to it. Set the Image component's Sprite to the cursor image you want to use, and then set the Canvas UI object's Event Camera to the camera you want the cursor to appear in front of.


#Tip 117.

If you crop a bitmap in C#, you end up with another bitmap.  This is usually not what you want.  So, you have to change your Bitmap Size:

// I crop in this "crop" method.
public Bitmap CropImage(Bitmap source, Rectangle section)
{
// An empty bitmap which will hold the cropped image
Bitmap bmp = new Bitmap(section.Width, section.


#Tip 118.

To make a unit move towards a target continuously, use the following pattern:

var targetPosition = new Vector3(10, 0, 0);

while (true)

{

transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime);

if (transform.position == targetPosition)

{

break;

}

yield return null;

}


#Tip 119.

If you need to sort a list of objects by a property, you can use the System.Linq.OrderBy extension method. For example, if you have a list of objects with a "Name" property, you can use the following code to sort them alphabetically:

var sortedList = myList.OrderBy(x => x.Name);


#Tip 120.

use an AstarPath object to create and manage a pathfinding graph for your game.

1. In the Unity editor, create an AstarPath object from the menu (GameObject->AstarPath).

2. Place the AstarPath object in the scene where you want the pathfinding graph to be located.

3. Configure the AstarPath object's settings as desired.

4. Use the AstarPath object's methods to add nodes and


#Tip 121.

When you're working with rotations a lot, it can be helpful to use the Quaternion.Euler method to create new rotations. This method accepts three float parameters for the x, y, and z axes, and returns a new Quaternion rotation.

You can use the Quaternion.Euler method like this:

Quaternion myRotation = Quaternion.Euler(x, y, z);


#Tip 122.

develop all MonoBehaviour scripts openly in Visual Studio, but compile them in Unity's IDE.

This is a great programming pattern tip for developing MonoBehaviour scripts in Unity. By developing the scripts openly in Visual Studio, you can take advantage of all the features that Visual Studio has to offer, such as code completion and IntelliSense. However, when it comes time to compile the scripts, you can do so in Unity's IDE, which will ensure that the scripts are properly compiled for


#Tip 123.

override the default ToString method.

This is helpful if you want to control how an object is represented as a string. For example, you might want to control how a DateTime object is displayed.


#Tip 124.

For a quick way to see if a given Vector3 is facing another Vector3, you can use the Vector3.Dot() method. Simply provide the Vector3 you wish to check as the first parameter, and the Vector3 you wish to check against as the second parameter. If the result is positive, then the first Vector3 is facing the second Vector3.


#Tip 125.

When you want to create a new object, always use the "using" statement. This will ensure that the object is properly disposed of when you're finished with it.

Here's an example:

using (MyClass myObj = new MyClass()) { // Use myObj here }


#Tip 126.

You can use coroutines to wait for a certain amount of time before executing a certain line of code. For example, you could use a coroutine to make a character wait for 5 seconds before attacking.


#Tip 127.

If you need to loop over a set of items multiple times, but in different ways, you can use a yield return loop.
Here's how it would work in your case:

public static void Main(string[] args)
{

    var takeTen = GetTenItems();
    foreach (var item in takeTen)
    {
        Console.WriteLine(item);
    }

    var takeFifteen = GetFifteenItems


#Tip 128.

If you need to move an object around the scene without using the Unity editor, you can use the "Move Tool" (W key) to click and drag the object around.


#Tip 129.

Alwaysuse the var keyword when assigning variables. This will help ensure that you are using the correct data type for the variable, and it can also help make your code more readable.


#Tip 130.

As you have your code above, you could implement this LINQ query:

var matchingEntries = yourList.Where(x => (x.Length >= 5 && x[3].Equals(' ') && x[4].Equals(' ')))
            .Select(r => new
            {
                /*whatever*/
            });


#Tip 131.

The standard pattern for dealing with callbacks in Unity is:

EventSystem.current.ExecuteEvents<T> (PointerEventData eventData, ExecuteEvents.EventFunction<T> functor);


Example:

using UnityEngine;
using UnityEngine.EventSystems;

public void OnPointerDown (PointerEventData eventData) {
    //


#Tip 132.

To check if a string is empty, you can use the IsNullOrEmpty method:

string s = "";

if (string.IsNullOrEmpty(s))
{
   // The string is empty.
}


#Tip 133.

If you want to create a game object at runtime and add it to the scene, you can use the Instantiate() method. For example, if you have a prefab named "MyPrefab", you can do this:

GameObject myObject = (GameObject)Instantiate(Resources.Load("MyPrefab"));


#Tip 134.

use the UnityInputManager to set up key and mouse input. First, create a script and add the following code:

InputManager.Instance.SetupInputManager();

Now, in the Update method of your script, you can check for input like this:

if (InputManager.Instance.GetKeyDown(KeyCode.Space)) { // do something }

This is a great way to set up input in Unity, and it's very easy to use.


#Tip 135.

If you find yourself constantly needing to check for null values, consider using the ?? operator. For example, instead of writing:

if (myString != null)

{

//do something

}

You can write:

myString = myString ?? "default value";

This will set myString to "default value" if it is currently null.


#Tip 136.

If you want to create a custom mesh, you can use the Unity 3D Probuilder tool. This tool allows you to create and edit 3D meshes directly in the Unity editor.


#Tip 137.

You can create a list of custom objects who's property values are the same as another list of objects by doing the following:

List<CustomClassB> myCustomList = myListOfObject.ConvertAll(item => new CustomObjB(item));


This is assuming your CustomClassB constructor is setup to receive your generic class.


#Tip 138.

You can make a C# script that can create a prefab out of a model that you've selected in the Project View.

To do this, you'll first need a model that you've imported into your Unity project. Once you have that, create a new C# script and attach it to an empty GameObject in your scene. Then, paste the following code into your script:

using UnityEngine;
using UnityEditor;

public class CreatePrefab :


#Tip 139.

If you have a method that needs to be called every frame, consider using the Update() method.


#Tip 140.

If you ever need to make a deep copy of an object, you can use the System.Reflection.MemberInfo.Copy method. This method makes a copy of all the fields in an object, including any nested fields.


#Tip 141.

it's rarely better to return early from a method.

There are situations where it's more convenient to return early from a method, for example when you need to check for valid input before doing any work. However, this can lead to code that's harder to read and maintain. It's usually better to put all the checks at the beginning of the method and then do the rest of the work. This makes the code easier to follow and makes it clear what the method is supposed to do


#Tip 142.

". This example is intended to grab your attention and illustrate a wide variety of C# features in a concise manner. Topics included:


-idioms
-patterns
-features
-control flow
-best practices


#Tip 143.

If you have a sequence of data objects - each with a unique key/ID - and you want to perform a set of operations on each data object (e.g. update a database, write to a file), it's usually best to use a Dictionary to hold your data objects, rather than a List.
A Dictionary can be thought of as a type of Hashtable, which gives you very fast access to your data records.
KeyedCollections are basically a Dictionary with


#Tip 144.

In C#, you can use the "goto" keyword to jump to a label.


#Tip 145.

If you have an object that you want to move along a path, you can use the Unity 3D NavMesh system.

To set up a NavMesh, you first need to create a NavMesh Asset. This can be done by selecting Assets >Create >NavMesh Asset in the Unity menu bar.

Next, you need to add a NavMesh Agent component to your object. This can be done by selecting Add Component >NavMesh Agent in the Inspector.

Finally


#Tip 146.

using UnityEngine; using System.Collections; using System.IO;
public class ExampleClass : MonoBehaviour
{ string time; public float minutes; public float seconds; public float frames;



void example ()
{
time= minutes.ToString("00")+":"+seconds.ToString("00")+":"+frames.ToString("00");


#Tip 147.

If you have a Unity C# script that's making use of a lot of different objects in the scene, a good tip is to make all of your object references public, but also make them all optional (i.e. have default values of null).

This way, you can easily assign the objects you need in the Inspector without having to constantly re-assign them in code, and if you ever need to change an object reference, you can just do it in the


#Tip 148.

"Avoid storing too much data in object state, but rather pull data from a data store when it is needed."

For example, if you have an object that represents a user, you might be tempted to store all of the user's data in the object. However, it's usually best to only store the data that is absolutely necessary in the object, and to query a database or other data store when more data is needed. This can help keep your code more maintainable and scalable.


#Tip 149.

if you have an IEnumerator function like "DoWork," you can skip over waiting time in a script by calling
DoWork from a different script, without having to wait for the original script to finish.

public class A : MonoBehaviour
{
  void Start()
  {
    StartCoroutine(DoWork());
  }

  IEnumerator DoWork()
  {
    print("Doing work");
    yield


#Tip 150.

use a utility class to expose current scene data in GameEditor only; call method in that utility class to set the data up; in final builds, you can expose data through serialized variables in a MonoBehaviour, but use a fallback value for the case those variables are zero (prefab / nothing in the scene yet).
This example has a "key" variable in a utility class, and a "GetKey" method. On game start, the size of the key and the


#Tip 151.

When working with the various data types in C#, it is often necessary to convert values from one type to another. A common programming pattern is to use the "as" keyword to attempt to convert a value to a specified type, and then check to see if the conversion was successful:

int i = 10;

float f = (float)i;

Console.WriteLine(f); // Prints 10.0

However, this pattern can lead


#Tip 152.

If you want to convert a string to a byte array, you can use the Encoding.UTF8.GetBytes method.


#Tip 153.

If you have a property, event or method that needs
to fire a series of actions till completion, but the
completion condition is not known beforehand,
encapsulate these actions within a method
with an infinite loop. Breaking out of the loop
should be done as the last action of one of
the encapsulated methods. Note also that it's a good idea
to pass a cancellation token into the methods, so that
the loop can be broken out of programatically


#Tip 154.

Remember that LINQ is a functional programming language, so you can use higher-order functions. This means that you can create LINQ expressions that take other LINQ expressions as input. For example, you could create a LINQ expression that takes a list of numbers and finds all the numbers that are divisible by 3.


#Tip 155.

If you want to add a force to a rigidbody in Unity, you can use the AddForce() method. For example, if you have a rigidbody named "rb" and you want to add a force of 10 in the positive x direction, you can use the following code: rb.AddForce(new Vector3(10, 0, 0));


#Tip 156.

If you want to create a new object, you can use the new keyword. For example, if you wanted to create a new instance of the System.IO.FileStream class, you would use the following code:

FileStream fs = new FileStream("myfile.txt", FileMode.Open);


#Tip 157.

If you want to move an object around the scene, you can use the "Move Tool" (W). To select it, just click on the "W" in the top left corner of the Unity editor. Then, you can click on the object you want to move and drag it around.


#Tip 158.

If you want to declare a variable that can hold multiple values of the same type, you can use an array.

For example, if you want to create an array of integers, you would declare it like this:

int[] myArray;


#Tip 159.

Let's say you want to load an image from a file into a bitmap but you want your own custom error handling. You can do this easily by using the Bitmap constructor that takes a stream as a parameter.

First, you need to open a stream to the image file. You can do this with the FileStream class:

FileStream stream = new FileStream("pathtofile", FileMode.Open);

Then, you can use the stream to construct a


#Tip 160.

Assuming you have a string variable named exampleString, you can find its length by using the .Length property:

exampleString.Length;


#Tip 161.

There's a way to make an object float up and down, and it's really simple! All you need to do is add a Rigidbody to your object, and then add a script with this code:

void Update()
{
    float y = Mathf.Sin(Time.time);
    this.transform.position = new Vector3(this.transform.position.x, y, this.transform.position.z);
}


#Tip 162.

If you want to keep track of how many times a certain method is called, you can use the [System.Diagnostics.Conditional("UNITY_EDITOR")] attribute. This will only compile the method calls when the Unity editor is running, which is useful for debugging purposes.

For example:

[System.Diagnostics.Conditional("UNITY_EDITOR")] void MyMethod() { // ... }


#Tip 163.

If you want to have a smooth camera movement in Unity, you can use the "SmoothDamp" function. This will take your current camera position and target camera position and smoothly move the camera towards the target position.


#Tip 164.

If you need some value, but the method for getting that value may not exist, it's best to leave collecting that value up to the actual consumer of the value.
In this way, the consumer of the value can decide what to do if the value cannot be obtained.
Here's an example:
Say you are making a method that formats a string based on some value.
You may want to obtain that value from a configuration setting.
However, you cannot


#Tip 165.

If you need to generate a random number in C#, you can use the System.Random class.


#Tip 166.

If you find yourself repeatedly writing code that does the same thing in different ways for different types, it's a good idea to use the built-in C# type system to write more general code.

For example, if you have a function that needs to take different actions depending on the type of object it is given, you can use the 'is' keyword to check the type of the object:

if (obj is SomeType) { // do something } else if


#Tip 167.

You can easily create extension methods for custom types!

Creating an extension method is simple. First, create a static class. Then, add a static method that takes in your custom type as the first parameter (marked with the "this" keyword). From there, you can add whatever functionality you want inside your extension method.

Here's an example:

public static class ExtensionMethods { public static void MyExtensionMethod(this MyCustomType myObject) { //


#Tip 168.

To convert a string to a byte array, you can use the System.Text.Encoding.ASCII.GetBytes() method.


#Tip 169.

It's generally good practice to use the "using" statement when working with IDisposable objects. This will ensure that the object's Dispose method is called when it is no longer needed, which helps to prevent memory leaks.

For example:

using (SomeIDisposableObject obj = new SomeIDisposableObject()) { // Use the object here. }


#Tip 170.

If you want to create a custom inspector for a script, you can create a class that inherits from UnityEditor.Editor. This class must be placed in a file called "Editor" in your project, and the name of the class must end in "Editor". For example, if your script is called "MyScript", you would create a class called "MyScriptEditor" in a file called "MyScriptEditor.cs" in an "Editor" folder.


#Tip 171.

If you find yourself repeatedly writing similar code blocks, it's probably a good idea to create a method that encapsulates that code. This makes your code more concise and easier to read, and it also makes it easier to modify the behavior if you need to make changes later on.


#Tip 172.

if you can't immediately tell which method is going to be executed here, you are writing bad code.

In this case, it is not immediately clear which of the three methods is going to be executed. All three methods have the same name, and all three methods take the same type of parameter.

The correct way to write this code would be to make it clear which method is going to be executed:

public void DoSomething(int x) { if (x ==


#Tip 173.

Use the "using" keyword when working with Unity objects.

For example, if you have a GameObject named "myObject" and you want to access its Transform component, you would use the following code:

using (Transform t = myObject.transform)

{

// do something with the Transform component

}


#Tip 174.

you can use the String class's
Concat method to concatenate two strings together. For example:

string s1 = "Hello";
string s2 = "World";

string s3 = String.Concat(s1, s2);

Console.WriteLine(s3); // Prints "HelloWorld"


#Tip 175.

Try using the String.Format method to improve the readability of your code. This method can help you insert values into a string template in a more readable way.


#Tip 176.

<blockquote>
<p>If you want to convert a string to a
  number, you can use the
  int.Parse(string) or
  float.Parse(string) methods. For
  example, the following code converts
  the string "1234" to the integer
  1234.</p>
<pre>
<code>int i = int.Parse("1234");
&


#Tip 177.

If you want to create a delay in your code, you can use the Invoke method. For example, if you want to wait 2 seconds before running some code, you can use:

Invoke("MyFunction", 2);

where "MyFunction" is the name of the function you want to run.


#Tip 178.

If you have a list of things, you can use a "foreach" loop and "continue" on any conditions inside the loop. So if you want to skip processing any files that have a .bak extension, for example, here's the basic idea for moving a directory of files.

string path = @"c:\temp\testfolder";
int count = 0;

foreach (string f in Directory.GetFiles(path))
{


#Tip 179.

If you want to be able to see what a certain function does without having to go through the hassle of setting up a debugging environment, you can use the System.Diagnostics.StackTrace class.

StackTrace trace = new StackTrace();

foreach (StackFrame frame in trace.GetFrames())

{

MethodBase method = frame.GetMethod();

// do something with the method information

}


#Tip 180.

If you're processing a bunch of requests all at the same time, schedule the requests by starting and stopping them all at the same time as opposed to scheduling each request individually and then starting and stopping all of them. By doing it this way, you'll avoid having to wait for each request to finish before starting the next one.

For example, consider a scenario where you're processing a bunch of images. You could start by scheduling all of the requests at the same time, then wait for


#Tip 181.

if you have a Component class that inherits from MonoBehaviour , you can have that class expose properties and methods through an interface to make it easier for scripts that use that shared functionality to find and call the functionality.

Here's a sample interface class from a Service Locator implementation:

public interface ILocatableService { Vector3 restPosition { get; } Vector3 Lerp(Vector3 v1, Vector3 v2, float t); }

Now here's


#Tip 182.

In the using block, you can take advantage of the fact that you can use a method within the using statement

using (GetConnection())
{
  //do something interesting
}


In the using block, you are able to use the method
GetConnection
which will establish a connection.  By doing this, you are able to use the
using
block to control the connection to the resource.


#Tip 183.

* When working with data, create a helper method that can be used to easily access and manage that data.

This will make your code more readable and maintainable.


#Tip 184.

<br>";
var tipContent2 = tipNum[Random.Range(0, tipNum.Count)];
tipText.text = tipContent1 + tipContent2;
}
}


#Tip 185.

Remove duplicates by using the Distinct method defined on IEnumerable, then chain the OrderBy Method diretly after.

results.Select(r=>r.Model).Distinct().OrderBy(r=>r)


#Tip 186.

You can use the gaze manager to input data into your game by using your eyes!

1. To do this, first make sure that the gaze manager is included in your scene.

2. Next, create a script that includes the following code:

void Update() { if (GazeManager.Instance.Hit) { // Do something here when the player is looking at something! } }

3. Attach this script to your main camera.

4


#Tip 187.

To ensure that a method is only called once, use the System.Lazy<T> class.

Lazy<T> provides a thread-safe way to lazily initialize a variable, ensuring that the variable is only initialized once. This can be especially useful when initializing expensive objects.

For example, consider the following code:

public static class MyClass { private static Lazy<MyObject> _lazyMyObject = new Lazy<My


#Tip 188.


yield return null;
inside a
IEnumerator
method gives Trinity OS stuff time to load or do what it needs to do before going to the next line of code.


#Tip 189.

In C#, it is often useful to create extension methods. Extension methods allow you to "add" methods to existing types without having to create a new derived type. For example, suppose you have a class called MyClass, and you want to add a method called MyMethod to it. You can do this by creating a static class with a static method like this:

public static class MyClassExtensions { public static void MyMethod(this MyClass myClass) {


#Tip 190.

If you have a method that needs to be called every frame, use the Update() method.

If you have a method that needs to be called every fixed update, use the FixedUpdate() method.


#Tip 191.

do your work in *public static methods,* or in *static methods called via through a public static actor.*

There are two main reasons for this. First, it makes your code much more testable. Second, it makes it easier to find and reuse your code later on.

For example, let's say you want to write a method that fades out a game object over time. You could write it like this:


csharp
public static class F


#Tip 192.

if you want to perform a non-null check, use it like this:

if (variable != null)
{
    // do something with variable
}

This is usually preferable to using an if-else statement, which would look like this:

if (variable == null)
{
    // handle null case
}
else
{
    // do something with variable
}

The reason the first pattern is preferable is because it is more


#Tip 193.

set `TextBoxBase.UseSystemPasswordChar` to true to make the text box display asterisks instead of the characters that are actually typed.


#Tip 194.

If you want your script to be accessible in editor windows like the Inspector, add the Serializable attribute
(e.g. in the class definition).

Here's an example:

[Serializable]
public class MyClass
{
   public int myInt;
   public string myString;
}


#Tip 195.

Find the object which has the component you want to access:

GameObject go = GameObject.Find("MyObject");

Component component = go.GetComponent("MyComponent");


I wouldn't use this method if you are planning on adding and removing the component in the Unity editor though. I would instead use:

Component component = GetComponent("MyComponent");


I'm sure there are other ways too


#Tip 196.

Create New Behaviour Parent game objects to empty game...

Objects can be parented to other objects in the hierarchy. This can be used to create groups or to constrain object motion. For example, you might want to parent a character's arm to their torso, so that it moves with the character. To do this, select an object in the Hierarchy window, and then drag the object you want to parent it to and drop it on top of the first object. The first


#Tip 197.

In C#, you can use LINQ to access data from a database. LINQ is a powerful tool that can help you easily query and manipulate data. To learn more about LINQ, check out Microsoft's documentation.


#Tip 198.

When working with Unity, it's often a good idea to use the "singleton" pattern for your game's main manager objects. This ensures that there is only ever one instance of the object in question, which makes it easier to access from anywhere in your code.

To implement the singleton pattern in Unity, simply create a static class with a static instance property of the type you want to make into a singleton. Then, in the Awake method of your game's


#Tip 199.

you can use the "Hash" function to create a number based on an unknown block of data. The number will be the same each time you feed in the same data. This is how a lot of games store information like player names and passwords; the game takes the input, hashes it, and compares the result against what's expected. If they're the same, then it's a match.

You can read more about hashing here:

https://en.wikipedia.org/


#Tip 200.

if you want to get the type of an object, you can use the GetType() method.

For example, if you have an object called myObj, you can get its type like this:

Type myObjType = myObj.GetType();


#Tip 201.

private static class LocalPrivateState { static LocalPrivateState() { // your own initializers go here } } Thanks to IntelliSense and C#'s static classes feature, you can easily pull additional local private state into the class without breaking existing code. For example: namespace MyProject { internal static class GlobalPrivateState { //Your state here... } private static class LocalPrivateState { static LocalPrivateState() { //Delete this when done developing TestInitialize(); //Set a breakpoint


#Tip 202.

Try to keep your code as modular as possible. That is, write small pieces of code that each perform a specific task, and then string those pieces together to create more complex behavior. This will make your code morereadable and easier to debug.


#Tip 203.

If you want to make a highly optimized game, it is often a good idea to use a custom shader. This way you can tailor the shader specifically for your game engine and your target platform. This can result in a significant performance boost.


#Tip 204.

If you want to create a multiline string, you can use the @ symbol before the string literal. For example:

string s = @"This is a

multiline string";


#Tip 205.

If you're working with Lightmaps in Unity 3D, you can use the LightmapScale property on your materials to fine-tune the brightness of your lightmaps.


#Tip 206.


public class Blade : MonoBehaviour
#if UNITY_EDITOR
, ISerializationCallbackReceiver
#endif

{

#if UNITY_EDITOR
[CustomEditor(typeof(Blade))]
public class BladeEditor : Editor
{
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        List<SerializedProperty> allProperties =


#Tip 207.

If you need to convert a string to a number, you can use the "Convert" class. For example, to convert a string to an integer, you would use the following code:

int num = Convert.ToInt32("123");


#Tip 208.

the
         * "using" keyword, when applied to classes, is essentially the same
         * as a "try/finally" block. So, with this in mind we can rewrite our
         * Update() method to look like this
         */
        using (new ReviveTriggerHelper(cardName))
        {
            Update();
        }
        /*
         * Let's use this extra flexibility to dynamically administer our data,
         * defining


#Tip 209.

try {
  // Code that could throw an exception
}
catch (System.Exception e) {
  Debug.LogException(e);
}


#Tip 210.

if you need a thread-safe method (say, a property setter method), make the method synchronous.  This is discussed in Piers Cawley's blog: http://www.improvingjava.c om/2012/03/if-you-make-your-methodsynchronized.html
For example:

public int MyProperty
{
    get
    {
        lock (locker) {
            return _myProperty;


#Tip 211.

To make your code more readable and maintainable, it is often a good idea to wrap code that is executed multiple times in a method. This way, you can centralize the code and make it easier to modify later on.

For example, let's say you have a loop that iterates through a list of objects. Instead of writing the loop code inline, you could move it to a separate method:

public void ProcessList(List<object> list) {


#Tip 212.

Write your code so that you can handle exceptions relatively gracefully. Don't bring your whole game to a crashing halt because one method itself has encountered an exception. That results in an infinite loop of error reporting, which the user can't get out of. It's better to catch exceptions and be graceful.

In this example, we use a custom made check method which does not throw exceptions, but just prints out an error message and then returns.

try { check(); } catch (


#Tip 213.

<blockquote>
<p>All public methods should go in the
  interface.</p>
</blockquote>
For sample code:

interface IInterface
{
    public void Method();
}

public void Method()
{
    //code here
}


#Tip 214.

If you want to create a realistic water effect, you can use a camera with a refraction shader. This will allow you to see objects below the water's surface as if they were being viewed through a glass.


#Tip 215.

+
+Always favor composition over inheritance.
+
+In other words, it's usually better to design your types so that they contain other types, rather than deriving from other types. This gives you more flexibility and makes your code more maintainable in the long run.


#Tip 216.

If you want to create a new object and initialize it with some default values, you can use the object initializer syntax. For example, if you want to create a new Point object with the default values of (0,0), you can write the following code:

Point point = new Point { X = 0, Y = 0 };


#Tip 217.

If you need to convert a string to a byte array, you can use the System.Text.Encoding.ASCII.GetBytes() method.


#Tip 218.

Always try to use the most specific type possible when declaring variables. For example, instead of using the "object" type, use a more specific type such as "string" or "int". This will make your code more readable and maintainable.


#Tip 219.

If you ever find yourself needing to do something repeatedly in a Unity project, chances are there's a better way to do it.

For example, if you need to constantly check if a certain condition is met, instead of writing a bunch of if statements everywhere, you can create a dedicated script to handle that.


#Tip 220.

If you want to create a simple audio visualizer, you can use the Audio Source component and the Line Renderer component. First, add an Audio Source component to your GameObject and select an audio file. Then, add a Line Renderer component and select a 2D line. In the Line Renderer component, set the Start Width and End Width to 0.1.

Next, create a script and attach it to your GameObject. In the script, create a float


#Tip 221.

If you want to make a game object move towards another object, you can use the "Look At" function. All you need to do is set the object's "transform.LookAt" property to the other object's position. For example:



transform.LookAt(otherObject.transform.position);


#Tip 222.

don't even bother adding Click Detector scripts to objects only to assign them to the current player inventory. Yes, it makes the code cleaner when the codegolfer and his agent gather the inventory and do all sorts of stuff with it...but that's not Unity. You don't need to do this there.

Just have an OnTriggerEnter or similar method on the player, spawn a prefab, then have a script on the spawned item to detect if it hits an inventory


#Tip 223.

When modifying an object's properties that might trigger other events during their changes (such as other property modifications, UI updates, progress bars, etc), it's best to make those modifications in a method that disables those events just before starting the modifications, and re-enables them when the modifications are complete.

This is often referred to as a "disabling events" or a "suspending events" pattern.

For example, if you have a "health" property on a


#Tip 224.

Use the Select statement to transform one sequence into another.


#Tip 225.

If you have a game object in your scene that you need to access often, you can make it a global variable so that it can be easily accessed from anywhere in your code.

To do this, simply declare the variable like so:

public static GameObject myGameObject;

And then you can access it from anywhere in your code by using MyClass.myGameObject.


#Tip 226.

Use Tuples!

C# tuples are great for creating simple data structures that can be used to store related data. You can create a tuple by using the following syntax:

var myTuple = (item1, item2);

You can then access the data in the tuple by using the following syntax:

var item1 = myTuple.Item1;

var item2 = myTuple.Item2;


#Tip 227.

Several of the built-in C# types (like float, double, int, and long) have an "IsNaN" method. This can be used to detect when your value has some weird number that should never happen. For example, it can detect when there is an error in a calculation. (Error numbers are usually not equal to zero, and are sometimes negative).
Calling it is pretty easy: just put "IsNaN(yourValue)" as a condition.


#Tip 228.

We had a project completed using Linq-To-Entities that required a way to retrieve multiple "hole" objects based on some parameters but it turned out that sorting was causing issues. By resorting to a stored procedure, the problem was alleviated.


#Tip 229.

The "RenderDoc" tool is really useful for tracking down graphics-related issues in your Unity projects.


#Tip 230.

If you want to add two numbers in C#, you can use the following code:

int result = num1 + num2;


#Tip 231.

If you want to create a copy of an object, you can use the "clone" method.


#Tip 232.

If you want to display a message in the console, you can use the following code:

Debug.Log("This is my message");


#Tip 233.

<blockquote>
<p>Use the null-coalescing operator to
  prevent Exceptions</p>
</blockquote>
Example:
Bad programming practice

Database db = null;
db.InsertTasks(MyTasks);


Good programming practice

Database? db = null;
db?.InsertTasks(MyTasks);


If you have a nullable object


#Tip 234.

You may be tempted to make your catch blocks 'catch-all' types. For example:

try
{
   // Do some work
}
catch (Exception ex)
{
   // Handle the exception
}
However, this is generally a bad idea. Catching Exception (or any base class)
will also swallowing more specific exceptions that may occur. For example, a
FileNotFoundException thrown by File.Open will not be caught if you


#Tip 235.

When you add something to your program that might throw an exception, put the code in a try/catch block.

C# is a great programming language that is very powerful and versatile. However, as with any language, it is important to be aware of potential errors that might occur. By using a try/catch block, you can ensure that your code will not crash if an exception is thrown.


#Tip 236.

If you click on the name of a C# file in the Unity Editor, it will open the file in your chosen code editor.


#Tip 237.

If you want to create a realistic water effect, you can use a shader. A water shader will give your water a realistic look and feel, and it can also be used to create other effects like rain or snow.


#Tip 238.

Use immutability wherever possible:

public class MyClass
{
    private readonly string _myField;

    public MyClass(string myField)
    {
        _myField = myField;
    }

    public string MyField
    {
        get { return _myField; }
    }
}

This way, you can be sure that the value of _myField will never change after the initial assignment.


#Tip 239.

If you need to create a new object and initialize it with some values, you can use the object initializer syntax. For example, let's say you want to create a new Person object and set its Name and Age properties:

var person = new Person { Name = "John", Age = 30 };


#Tip 240.

always create & use Global.asax. It doesn't hurt anything to have it there, and it's good practice for working within the ASP.NET runtime.

If you don't have a Global.asax, ASP.NET will happily work anyway, but you won't be able to take full advantage of some runtime features. For example, if you want to be able to handle application-level events (like Application_Start and Application_End), you need to have a Global


#Tip 241.

pChange the name of your void OnGUI fuction to something else. In C# you can't have more than one function per file with the same name.



meshmaniac 2003-12-18 20:40:47 EST Thanks for your advices, I have made some of his

suggestions. Also, I have compared

my code with the one tjs version and found that

they are not idential, but some different

in content


#Tip 242.

If you want to add a little bit of variety to your game, you can use the "Random.Range" function to generate random numbers. For example, you could use it to generate a random number between 1 and 10, and then use that number to determine which enemy spawns.


#Tip 243.

If you want to improve your workflow in Unity 3D, try using custom editor scripts. With editor scripts you can add custom functionality to the Unity Editor, making it easier and faster to work with.


#Tip 244.

If you have a case block, and some of the cases may be parsing or otherwise retrieving data, have a default case that contains the return statement, so you only have to code the return statement once.

For example:

string input = "5"; int result; switch (input) { case "1": case "2": case "3": result = int.Parse(input); break; case "4": result = 4; break; default: return -1


#Tip 245.

Assuming the products have the same name and has a different ID:

public Component[] AddMissingItemParts(){
    Component[] components_itemParts = UnityEngine.Object.FindObjectsOfType<Component>();
    Component[] components_products = UnityEngine.Object.FindObjectsOfType<Component>();
    var parts = from part in components_itemParts
                 where !components_products


#Tip 246.

You can use the string.Format() method to insert variables into a string template. For example:

string message = string.Format("Hello, {0}! Welcome to our website.", userName);

This would insert the value of the userName variable into the string at the {0} position.


#Tip 247.

If you need to move a player or object around the scene using code (instead of the Transform component using the mouse in the scene view), you can use the transform.Translate or transform.position to do so.

Here is an example of how you could use transform.Translate to move a player forwards:

transform.Translate(Vector3.forward * Time.deltaTime * speed);


#Tip 248.

If you want to create a list of items that you can add to or remove from, you can use the List<T> class.


#Tip 249.

If you find yourself writing a lot of code that looks like this:

if ( someCondition ) { // do something } else { // do something else }

You can simplify it by using the ternary operator:

// equivalent to the code above someVariable = someCondition ? valueIfTrue : valueIfFalse ;

This can be especially useful when setting the value of a variable based on some condition.


#Tip 250.

Try to avoid doing too much work in your constructors. Instead, move that work into separate methods that can be called when needed. That way, your constructors will be simpler and easier to read and understand.


#Tip 251.

If you want to create a custom inspector for a script, you can create an editor script. Editor scripts are special scripts that can be used to create custom inspectors, editors, and other custom tool windows.


#Tip 252.

whenever you have a giant pile of data stacked up (for example, database rows, RDF triples, or just plain old System.Collections.ArrayLists or System.


#Tip 253.

+
+If you find yourself frequently needing to check whether a particular component exists on a GameObject, it's often a good idea to create a property for it on your script. For example, if your script frequently needs to check whether a Collider2D component exists on a GameObject, you could create a property like this:
+
+public class MyScript : MonoBehaviour {
+
+    public Collider2D Collider { get { return GetComponent<Collider


#Tip 254.

Use the `#pragma` symbol to prevent compiler warnings from certain lines of code.

Here's an example:


csharp
#pragma warning disable CS0168 // Variable is declared but never used
int x;
#pragma warning restore CS0168 // Variable is declared but never used



The first line disables the warning for the `int x` line. The second line re-enables the warning


#Tip 255.

associate metadata with your code!

You can do this by using attributes. Attributes allow you to specify additional information about your code, which can be accessed at runtime.

For example, you could use an attribute to specify the author of a piece of code, or the date it was last updated.


#Tip 256.

If you create a method that can be called either synchronously or asynchronously, call it using the async keyword in the name.
For example  ImportAsync and Import.
This will reduce confusion down the road when you see the code later on, or someone else is working with it.
this goes against my original rule of thumb, but the compiler will issue a warning if the size of the method exceeds 100 lines, so that is a good check to see if it should


#Tip 257.

If you want to create a new list from an existing list, you can use the .ToList() method.

For example, if you have a list of strings called myList, you can create a new list of strings called myNewList like this:

myNewList = myList.ToList();


#Tip 258.

if you want to improve your performance and make your game run faster, you can use the "Static Batching" and "Dynamic Batching" options in the "Project Settings" menu. These options will help you optimize your game for better performance.


#Tip 259.

If you have a script that needs to do something every time the player presses a certain key, you can use the Unity Input Manager to set up an "Input Axis". Then, in your script, you can check the current value of that input axis, and if it's greater than 0, you know the player has just pressed the key.


#Tip 260.

If you want to create a custom inspector for a script, you can create an editor script. To do this, create a new script in your project and append the name of the script you want to create a custom inspector for with "Editor" (e.g. MyScriptEditor.cs). Inside this editor script, create a class that inherits from Editor and override the OnInspectorGUI method. This method will be called when the inspector is being drawn, so you can


#Tip 261.

One thing you can do in Unity 3D is create custom scripts. This allows you to add your own functionality to your games and apps. To do this, simply create a new script file in your Unity project. Then, open the file in your preferred code editor and add your code. Finally, attach the script to a game object in your scene to make it work.


#Tip 262.

if you want to assign each element in an IEnumerable to itself but with a different type (lets say you have a list of strings that you want to be converted to integers), you can map each of the elements to a parsable string and convert to an int as in the following example:

var result = strings.Select(x => int.Parse(x));


#Tip 263.

In C#, when you declare an event, the corresponding member variable should be private readonly

public class AnActionClass
{
  public event EventHandler SomethingHappened;
  private readonly EventHandler _somethingHappened;

  public AnActionClass()
  {
    _somethingHappened = new EventHandler(DoSomething);
  }

  public void OnSomethingHappens()
  {
    _something


#Tip 264.

If you want to change the value of a variable, you can use the "++" operator.

For example:

int myVar = 0;

myVar++;

This will change the value of myVar to 1.


#Tip 265.

To make a read-only Dictionary, you can use the System.Collections.ObjectModel.ReadOnlyDictionary class.


#Tip 266.

If you have an array of objects and you want to randomly select one of them, you can use the UnityEngine.Random.Range() method. For example, if you have an array of game objects called "enemyArray", you could use the following code to select a random enemy:

int enemyIndex = UnityEngine.Random.Range(0, enemyArray.Length);

GameObject randomEnemy = enemyArray[enemyIndex];


#Tip 267.

a simple way to make a menu that pauses a Unity game is to make a script with an
onGUI() function. This function will be called every frame that the game is paused, and you can use it to draw a menu.


#Tip 268.

in your program, you can keep track of the last time the user pressed a key, and if it's been more than a certain amount of time, you can automatically save the file. This is really useful if you're making a text editor or something similar.

To do this, you first need to create a timer object:

System.Timers.Timer timer = new System.Timers.Timer();

timer.Interval = 60000; // 1 minute


#Tip 269.

if you need to know if the player or some AI is facing something, code it so it proactively sets a bool like facingSomething=false when it's not facing the thing, and so it sets the bool to true while facing the thing.


#Tip 270.

Let's say you have an action, like Hit() or OnEventHappened() or something else that you wantYour custom FSMManagerMonobehaviour should persistent between scenes? Why? I guess the manager shouldn't track stuff of objects that are not in scene right? No, it shouldn't, but it may do stuff like load a bar, which you want to happen every time the... To reproduce: 1. Open the attached project "New Unity Project (4).zip"


#Tip 271.

When you have a public reference to an object (i.e. a method returns the object directly or a member is declared public), you generally want to make it a read-only or read-only Collection, if it's a collection type.

Just as an example, say you have a class with a public property like this:

public List<Foo> Items { get; set; }

Anyone can come along and modify the Items Collection directly, which is generally


#Tip 272.

In Unity C#, you can create an event that can be used to trigger other actions in your code. This can be useful for things like making a character move when a button is pressed.


#Tip 273.

Here's a tip for something you can do in Unity 3D:

If you want to create a realistic water effect, you can use the built-in Shaderlab water shader. To do this, first create a water plane object in your scene. Then, add a WaterBasicScript component to the object. This will give you access to the water shader settings. You can then adjust the settings to create different water effects.


#Tip 274.

If you need to call a function on all objects in the scene, you can use the Unity C# function "Object.FindObjectsOfType()" to get an array of all objects in the scene.


#Tip 275.

If you have a string with a value of "Yes" or "No" in it, and you want to convert the string to a Boolean value of true or false, you can use the following code:

bool.Parse("Yes") //returns true
bool.Parse("No") //returns false


#Tip 276.

You can use the "var" keyword to declare a variable whose type is inferred from the expression used to initialize it. For example:

var myList = new List<int>();


#Tip 277.

<blockquote>
<p>if (args.Count() > 0 && int.TryParse(args[0], out int portNumber))</p>
</blockquote>
But what should I do if an argument is not given?
<blockquote>
<p>if (args.Count() > 0 && int.TryParse(args[0], out int portNumber


#Tip 278.

You can create random spawn points in a 2D game by using a Perlin noise script and setting the y value to whatever y position you want the objects to spawn at.

Here's an example of how to do this:

public Vector2[] SpawnPoints; public float yPos = 10f; public void GenerateSpawnPoints() { SpawnPoints = new Vector2[100]; for (int i = 0; i < SpawnPoints.Length; i++) { SpawnPoints


#Tip 279.

if you use a List or an array and you Never insert or remove items from it, use a
ReadOnlyCollection<>
as a wrapper. This will make the methods
.Clear()
,
.Insert()
etc. not accessible, meaning anyone will receive a compiler error if they attempt to modify the set.
Another tip is to expose the collection only via a public property, and make the property itself read


#Tip 280.

If you want to create a realistic water effect, you can use a shader. Shaders are special programs that run on the GPU, and they can create some amazing effects.

To create a water shader, you'll need to create a few textures. First, you'll need a calm water texture and a moving water texture. You can create these yourself, or you can find them online.

Next, you'll need to create a shader. You can find a water shader


#Tip 281.

If you need to move an object smoothly over time, you can use the iTween plugin. iTween is a free plugin that gives you a lot of useful functions for moving, rotating, and scaling objects.


#Tip 282.

After an operator, and before a semicolon terminator, there must be a space.

If you put an operator and a semicolon terminator next to each other, the semicolon terminator will be ignored.


#Tip 283.

If you want to run some code every frame, the best way to do it is to create a MonoBehaviour script, and then add that script to a GameObject. Then, in the Update() method of your script, you can put your code.


#Tip 284.

If you need to convert a string to a float, you can use the System.Convert.ToSingle() method.


#Tip 285.

You can change how an unpublished script behaves in the editor without having to unpublish, change it, and republish.

To do this, go to the "Project" window, right-click on the script you want to change, and select "Reimport". This will cause Unity to re-evaluate the script and apply any changes you've made.


#Tip 286.

If a Tuple has four members, use Item4 instead of Item3. It makes the Code easier to read and eliminates magic numbers.</p>
</blockquote>
I've seen Item1, Item2, Item3 and Item4 in code. I understand why a developer would just write Item1, Item2, Item3 because the saying goes:
<blockquote>
<p>Don't use magic numbers in code. <em>Define variables and constants instead


#Tip 287.

If you're working on a game with a lot of different levels, it can be helpful to create a LevelManager script. This script can be in charge of loading and unloading levels, as well as keeping track of which level is currently active.

This script can be attached to a GameObject in your scene, and you can use the LevelManager to load levels from your script. For example, you could have a public function called LoadLevel() that takes a level index


#Tip 288.

creating a pause menu

In order to create a pause menu in Unity 3D, you will need to first create a Canvas. Once you have created a Canvas, you can then add a Panel to it. Inside of the Panel, you can then add Buttons, Text, and Images.


#Tip 289.

If you have a
List<string>
, you can use
String.Join()
to get a single string separated by a given character:

var list = new List<string> { "One", "Two", "Three" };
var string = String.Join("|", list);


This will give you a string
"One|Two|


#Tip 290.

You can use the "File" drop-down menu at the top of the Unity editor to access many different functionalities, such as importing assets, creating new scenes and assets, and opening the Unity Project Browser.


#Tip 291.

In order to create a believable simulation, it is important to add realism to your Unity 3D project through the use of audio. One way to do this is to add environmental sounds to your scenes. This can be done by using audio clips of different ambiences, such as wind, rain, or forests. You can also add Foley sounds, such as footsteps or leaves rustling, to add to the realism of your project.


#Tip 292.

If you want to animate a character or object in Unity 3D, you can use the animation tool. This tool allows you to create animations by specifying keyframes. Keyframes are points in time where you specify what the character or object should be doing.


#Tip 293.

If you're using Visual Studio, you can use the "Go To Definition" feature (F12) on any class, method, or property to jump to its definition in the code.


#Tip 294.

it's a good idea to make sure you've fetched all of the data you need to before you close the stream or reader.
For example:

for (stream)
{
    do something
}

// at the end of the using block

using (stream)
{
    for (stream)
    {
        do something
    }
}


#Tip 295.

If you want to create a custom editor for a script in Unity 3D, you can create a new script in your project and extend the Editor class. You can then override the OnInspectorGUI() method to draw your own custom editor.


#Tip 296.

do X if it happens first time, but don't if it happens 2nd time; do Y if it happens 2nd time, but don't if it happens first time.

if ( condition1 ) { // do X } else if ( condition2 ) { // do Y }


#Tip 297.

When you need to create an object that can be used by multiple threads, consider using the ThreadStaticAttribute to create a thread-specific instance of the object. This attribute ensures that each thread has its own instance of the object, which can be accessed using the static field that the attribute is applied to.


#Tip 298.

If you need to perform an operation on a large number of items in an array, you can use the System.Array.ForEach method. This method will iterate through each item in the array and perform the operation you specify.


#Tip 299.

When you need to refactor part of GameObjects behaviour in order to change things like the effect of a Raycast Hit or something, a generic function is a great attitude! This will allow you to ays the GameObject| without having to change the existing code around it.
The way to do it would be something like this:

public class MyClass
{
//...

    public void MyFunction<T>(T gameObject) where T :


#Tip 300.

Use precompiler directives (if, endif) to wrap all your custom code in debug vs. release versions.
For example:

#if (DEBUG)
    //Your debug code here
#else
    //Your release code here
#endif


The reason this is useful is that some of your debug code might slow down performance or throw exceptions that you wouldn't want in a release build.


#Tip 301.

Instead of doing this:is often better as:

public string Join(string[] parts) { return string.Join(", ", parts); }

I found these two examples in my company's (an SME) legacy code. Both cases of classes with static methods are you not able to inject any dependency and so they are global concerning the code. So this is a big loss of info over what it actually does.You might say nothing can happen here since it's only the


#Tip 302.

A good programming pattern to use in Unity is the singleton pattern. This pattern ensures that there is only one instance of a class created, and it can be accessed from anywhere in the code. This is especially useful in Unity, as it allows you to easily access game objects and components from any script.


#Tip 303.

If you need to process a lot of data, it is often more efficient to use a for loop instead of a foreach loop.

This is because a foreach loop has to create an enumerator object internally, which can be quite expensive.


#Tip 304.

whenever you create a new type, like a script for example, the first thing you should do is create a new folder for those types of things. For example, if you're making a bunch of player controller scripts, you should put all of those in their own "Player Controller" folder. Then, if you ever need to delete them all, it's very easy to do that.

This helps keep your project organized and makes it easier to find the files you're looking for.


#Tip 305.

You can use a struct to implement a flyweight pattern.


#Tip 306.

If you want to create a new material, select the shader you want to use for the material from the Shader drop-down menu in the Material Inspector. Next, click the New button next to the shader name. This will create a new material using the selected shader.


#Tip 307.

If you find yourself frequently having to write code that looks like this:

if (thing != null && thing.transform != null && thing.transform.position != null) {
    // do something
}

You can use the null-coalescing operator (??) to simplify it:

var position = thing?.transform?.position ?? Vector3.zero;

This will set the "position" variable to the "thing"'s position


#Tip 308.

If you have a list of objects and you want to order them by a certain property, you can use the OrderBy() method. For example, if you have a list of objects of type Person and you want to order them by their last name, you can use the following code:

var orderedList = listOfPeople.OrderBy(person => person.LastName);


#Tip 309.

If you want to make a gameobject move towards another gameobject, you can use the UnityEngine.Vector3.MoveTowards method.


#Tip 310.

If you want to create a new instance of a class, you can use the "new" keyword. For example, if you have a class called "MyClass", you can create a new instance of it like this:

MyClass myObject = new MyClass();


#Tip 311.

If you need to know the index of an element in an array, you can use the Array.IndexOf() method.


#Tip 312.

+
+The String.Format() method can be very useful for quickly creating strings from data. For example, if you want to create a string that includes the value of a variable, you can use String.Format():
+
+string s = String.Format("The value of the variable is {0}", variable);
+
+This is especially handy when you need to create strings that include data from multiple variables:
+
+string s = String.Format


#Tip 313.

In the Unity editor, you can hold down the alt key and left-click-drag to orbit the camera around the scene.


#Tip 314.

If you want to create a randomized number, you can use the UnityEngine.Random class. For example, if you wanted to generate a random number between 1 and 10, you could use the following code:



int num = UnityEngine.Random.Range(1, 10);


#Tip 315.

If you want to create a Destructible Mesh in Unity 3D, you can use the following steps:

1. Select the object you want to make Destructible.

2. In theObject Inspector, select Add Component > Physics > Destructible Mesh.

3. In the Destructible Mesh Settings, set the desired fracture level.

4. Play your game and destroy the object to see the fracture level in action!


#Tip 316.

If you want to add a component to an object dynamically (i.e. not in the editor), you can use the AddComponent() method. For example, to add a Rigidbody to an object:



Rigidbody rb = myObject.AddComponent<Rigidbody>();


#Tip 317.

<br>

You can use the "yield return null;" statement to force the Unity engine to wait one frame before continuing execution. This can be useful if you need to wait for something to happen before continuing.


#Tip 318.

If you want to change the color of an object in Unity 3D, you can use the "color" property in the "Renderer" component.


#Tip 319.

If you want to create a custom inspector for a script, you can create an editor script. To do this, create a new script and put it in a folder called "Editor" within your project's "Assets" folder. Then, decorate your script with the
[CustomEditor(typeof(YourScript)] attribute.

For more information, check out the Unity documentation on custom inspectors:

https://docs.unity3d.com/Manual


#Tip 320.

If you need to hold down a key constantly in Unity 3D (for example, to keep a character moving forward), you can use the Rewired Input Manager to do this. Go to Edit > Project Settings > Input Manager, and then create a new Input Axis. Set the "Axis" parameter to "Key or Mouse Button" and the "Axis Type" parameter to "Keyboard". Then, in your script, you can check the "GetButton" or "Get


#Tip 321.

If you want to move an object around the scene, you can select it in the Hierarchy panel and then use the arrow keys on your keyboard to move it.


#Tip 322.

Every time you change Scene your static field values reset. So if you set something in the static field in Scene 1 and then move to Scene 2  already meaning full values in the static field of Scene 1 lost
ANy time you need to save some info, use PlayerPrefs.
Information is persisted outside the Life Cycle of an application.


#Tip 323.

In LINQ, the Where operator is used to filter a collection based on a given predicate. The predicate is a function that takes an element of the collection as input and returns a Boolean value that indicates whether the element should be included in the output.

For example, the following code filters a list of integers based on whether they are less than five:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6,


#Tip 324.

To convert a string to a byte array, you can use the System.Text.Encoding.ASCII.GetBytes() method.


#Tip 325.

An expression that initializes a list of component references often uses Linq's Select function like so:

var components = gameObjects.Select(g => g.GetComponent<TooltipGUI>())
                            .Where(component => component != null);
foreach (var tooltipGUI in components)
{
    tooltipGUI.ShowTooltip();
}


Game objects that have


#Tip 326.


public static IEnumerable<Transform> GetObjectsWithTagRecursive(Transform obj, string tag)
{
    foreach(Transform t in obj)
    {
        if(t.tag == tag)
        {
            yield return t;
        }
        foreach(Transform t1 in GetObjectsWithTagRecursive(t, tag))
        {
            yield return t1;


#Tip 327.

You can use the System.Diagnostics.Stopwatch class to measure elapsed time.


#Tip 328.

When working with text, you can use the TextMesh component to easily add text to your scene. To do this, simply add a TextMesh component to your GameObject and then type your text into the "Text" field. You can also change the font, color, and size of your text using the TextMesh properties.


#Tip 329.

If you want to ensure that a particular method is only called once, you can use a bool flag to track whether or not it has already been called. For example:

private bool _methodCalled = false;

public void MethodToCall()

{

if (_methodCalled) return;

_methodCalled = true;

// method logic goes here

}


#Tip 330.

If you need to generate a random number in C#, you can use the System.Random class.


#Tip 331.

You can actually place objects or platforms in the game by using a separate Unity project and then copying the files into the appropriate folder in your project. This can be helpful if you want to test out something without having to rebuild your project.


#Tip 332.

If you want to create a custom inspector for your script, you can use the UnityEditor namespace. For example,

using UnityEditor;

[CustomEditor(typeof(MyScript))]

public class MyScriptEditor : Editor

{

public override void OnInspectorGUI()

{

//Your code here

}

}


#Tip 333.

If you want to convert a string to a byte array, you can use the System.Text.Encoding.ASCII.GetBytes() method.


#Tip 334.

If you enable character shadows in your Unity project, you can use a spotlight to create a shadow puppeteering effect!


#Tip 335.

When you have a reference to an object, always check if it's null before using it.

For example, let's say you have a reference to an Enemy object:

Enemy enemy;

Before using the enemy object, you should check if it's null:

if (enemy != null) { // Use the enemy object. }

This will help prevent NullReferenceExceptions from occurring.


#Tip 336.

If you want to create a more realistic lighting effect in your Unity 3D scene, you can use light probes. Light probes are essentially 3D textures that store information about the light in a particular area. By placing light probes throughout your scene, you can create a more realistic lighting effect.


#Tip 337.

when dealing with collection types, inherit from Collection<T> (C#) whenever possible.
While you're at it, prefer IList<T> over IEnumerable<T>; List<T> over IList<T>; and every one else over that.

Collection<T> provides you with a lot of methods for free, including Add, Remove, Clear, Contains, and more.
Inheriting from Collection<T> is usually pretty straightforward,


#Tip 338.

If you want to convert a string to a byte array, you can use the Encoding.UTF8.GetBytes method.


#Tip 339.

private readonly variables in .NET are not truly immutable. For example:

private readonly decimal mAmount = 10.0m;

That won’t stop you from being able to do this:

mAmount = 11.0m;

You will get a compiler warning; but it’s warning only, it won’t stop you from compiling and running the code.

It just forces you to declare any variable that you want to


#Tip 340.

Updating a value over time is a common game programming task. A simple way to do this is to keep track of the time since the last update, then multiply that by a rate to get the amount to update by.

For example, if you want to update a player's position by 10 units per second, you could do something like this:

float timeSinceLastUpdate = 0f;

void Update()

{

timeSinceLastUpdate +=


#Tip 341.


// SceneA.cs
public class SceneA : MonoBehaviour
{
    void Awake ()
    {
        SceneManager.LoadScene("B");
    }
}


But you might want to unload the old Scene if, for example, you want to go back to it via a button.

// SceneB.cs
public class SceneB : MonoBehaviour
{


#Tip 342.

The using statement is a good way to ensure that objects are properly disposed when they are no longer needed.


#Tip 343.

If you want to convert a string to all upper-case or all lower-case, you can use the ToUpper() or ToLower() method, respectively.


#Tip 344.

* Always deal with primitives in your operating system.

This will ensure that you don't run into any memory or pointer problems when dealing with your code.


#Tip 345.

If you want to create a custom inspector for a script, you can create an Editor script. This script should be placed in a folder called "Editor" and it will automatically be compiled by Unity. In this script, you can override the OnInspectorGUI() method to customize the inspector GUI for your script.


#Tip 346.

To make a Unity C# script execute code on a regular interval, use the InvokeRepeating() method. This method takes two parameters:

- The name of the method to execute
- The time interval (in seconds) between each execution

For example, to execute the Update() method every 0.5 seconds, you would use the following code:

InvokeRepeating("Update", 0.5f, 0.5f);


#Tip 347.

In Unity, it's often a good idea to make use of the "singleton" design pattern. This ensures that there is only ever one instance of a particular class, and that instance can be accessed easily from anywhere in the code.

To implement a singleton in Unity, simply create a static class with a static instance property:

public static class MySingletonClass { public static MySingletonClass Instance { get; private set; } private MySingleton


#Tip 348.

If you want to make a script that will execute some code when an object is clicked on, you can use the OnMouseDown() method.


#Tip 349.

If you want to find out how many lines of code are in a given file, you can use the File.ReadLines method. This method returns an IEnumerable<string>, so you can use LINQ to query it. For example, the following code would return the number of lines in a file named "MyFile.txt":

int lineCount = File.ReadLines("MyFile.txt").Count();


#Tip 350.

if you want to create a round object (e.g. a soccer ball or beach ball) you can use a Sphere Collider. Just add a Sphere Collider component to your object and make sure the "Is Trigger" option is unchecked.


#Tip 351.

The code

Object o=null;  //this is bad


is better as:

Object o;       //this is better


The reason being is that in the first line, it puts the value of null at a memory address that the variable o points to, while in the second it simple exposes the uninitialized variable o on the stack.
You can see the difference in the generated assembly code


#Tip 352.

http://blog.bauland.com/post/2008/12/08/Sorting-a-ListT-by-Two-Properties-in-C.aspx


#Tip 353.

Listen to Unity's message loop events. When that's something you want to do.

For example, the OnGUI event is called every frame that the GUI is enabled. So, if you need to do something every frame, like check for input, you can do that in the OnGUI event.


#Tip 354.

http://rich4291.blogspot.com/2011/07/APIs-programming-pattern-tip.html

It outlines a good paradigm for creating API like functions in C#, and how to make them more useful.


#Tip 355.

To concatenate two strings, you can use the "+" operator. For example, if you have two string variables, str1 and str2, you can concatenate them like this:

string str1 = "Hello";
string str2 = "World";

string str3 = str1 + str2;

// str3 now contains "HelloWorld"


#Tip 356.

If you want to change the position, rotation or scale of a GameObject in Unity, you can use the Transform component. Every GameObject has a Transform component by default.

To change the position of a GameObject, you can use the following code:

transform.position = new Vector3(0, 0, 0);

To change the rotation of a GameObject, you can use the following code:

transform.rotation = Quaternion.


#Tip 357.

If you need to generate a random number in C#, you can use the System.Random class.


#Tip 358.

If you want to invoke a method on a GameObject from another script, it's often useful to first check if the GameObject is null. This can be done using the "==" operator:

if (gameObject != null)
{
    // Invoke the method on the GameObject
}


#Tip 359.

In the Program.cs file of a console app, at the very top of the Main method, put a Console.ReadKey(); statement.

This will cause your console app to wait for a keypress before exiting.


#Tip 360.

If you want to create a new object in Unity, you can use the "GameObject" menu. To create a new object, select "GameObject" from the menu, then click "Create Other" from the submenu.


#Tip 361.

Whenever you can just return something
in a method instead of putting an output parameter on it, you should. Output
parameters are a sure sign of bad code. Instead return an out parameter. This
also fits the rule and keeps it consistent
With that being said, there are plenty of cases where out parameters are useful,
for example when you are dealing with optional parameters.


#Tip 362.

You can use the "Input.GetAxisRaw" function to get raw input from the user. This can be used to get input from a joystick, gamepad, or other device.


#Tip 363.

</b><br />Programmatic design of word documents in C# using Microsoft.Office.Interop.Word

This allows you to programmatically create and modify Word documents from within your C# code.


#Tip 364.

if you have a value with some types you need to do operations on, but you're not sure whether it's a type you especially care about yet, this template is more convenient than `if`/`else if`/`else`. More efficient, too: it runs faster.


csharp
var foo = someValue as Foo;
if (foo != null)
{
    // do something with foo
}


#Tip 365.

When working with the System.Collections.Generic namespace, it is often useful to create a static class with Generic extension methods. This allows you to add functionality to existing collection types without having to create new types.

For example, let's say you have a List<string> and you want to find all the elements that start with a given letter. You could write a LINQ query to do this, but it would be more convenient if you could just call a method on


#Tip 366.

To avoid code duplication, it is often a good idea to create a base class that contains the shared code, and then create subclasses that inherit from the base class and override the necessary methods.


#Tip 367.

If you want to create a custom inspector for a script, you can create an editor script. This script will be executed when the inspector is opened, and will give you full control over what is displayed in the inspector.


#Tip 368.

If you want to create a more realistic feeling in your game, you can use dynamic lighting. This means that the light will change based on the position of the player or other objects in the game. For example, if the player is in a dark area, the light will be dimmer. If the player is in a bright area, the light will be brighter. This can help create a more immersive experience for the player.


#Tip 369.

I have written a C# extension method which is being called excessively, and it's slowing my software. How do I do this?

One way to solve this is to cache the results of the extension method. This way, the method will only be called once for each unique input, and the results will be reused.

Another way to solve this is to use a statement block to only call the extension method when needed. For example, you could use a statement block like this:


#Tip 370.

whenever you see the type name of the object you don't need to look on the right side of the assignment to see what a method returns, just look on the left.

This is a good programming pattern tip for C#: whenever you see the type name of the object you are assigning to a variable, you can look on the right side of the assignment to see what type of object is being returned by the method. This can help you understand the code more quickly.


#Tip 371.

If you want to create a more realistic lighting effect in your Unity 3D game or application, consider using the Light Probe Proxy Volume component. This component can be added to any GameObject and will cause the object to cast light probes around itself, which can be used to create more realistic lighting.


#Tip 372.

Are you tired of needing to constantly call ToString() on an enum in order to get its string representation? Well next time, try using a const string array instead.

Here's how it would work:

public enum Fruit { Apple, Orange, Banana, }

public static class FruitExtensions { public static readonly string[] Names = new string[] { "Apple", "Orange", "Banana" }; }

Then you can use it like this:


#Tip 373.

To select random items from an
IEnumerable
use:

public IEnumerable<T> SelectRandom<T>(IEnumerable<T> source, int count)
{
    return source.OrderBy(x => UnityEngine.Random.value).Take(count);
}


For example:

var random


#Tip 374.

If you want to quickly create a new object at the same position and rotation as another object, you can use the Instantiate() method. Just pass in the object you want to clone, and Instantiate() will create a new object with the same transform.


#Tip 375.

To create a custom inspector for a script, create an Editor script and place it in a folder called "Editor" in your project. The script should extend the Editor class and override the OnInspectorGUI method. You can then use the EditorGUI class to create your own custom inspectors.


#Tip 376.

If you need to perform an operation on each element in an IEnumerable<T>, you can use the foreach loop. The foreach loop will iterate over each element in the IEnumerable<T> and perform the operation you specify.


#Tip 377.

Here's a good programming pattern tip for C#:

If you have a method that returns a value, you can use the null-coalescing operator (??) to provide a default value if the returned value is null. For example:

int? GetNullableInt() { … }

int GetNonNullInt()
{
    return GetNullableInt() ?? 0;
}


#Tip 378.

If you need to invoke a method on an object that may be null, use the null conditional operator:

var foo = GetFoo();
foo?.DoSomething();

This will check if foo is non-null before invoking DoSomething().


#Tip 379.

You can share files between your computer and your Android device by using the Android Debug Bridge (ADB).

To do this, you'll need to install the Android SDK on your computer. Once you've done that, you can use the ADB tool to transfer files between your computer and your Android device.

Here's how to do it:

1. Connect your Android device to your computer via USB.

2. Open a command prompt or terminal window on your computer


#Tip 380.

If you want to "do something" every frame, you can use the Update() method.

Here's an example:

void Update()
{
    //Do something every frame
}


#Tip 381.

Suppose you have an array of strings and you want to quickly determine
if any of the strings start with a given prefix.  You could do:

string prefix = "foo";
if (Array.Find(array, x => x.StartsWith(prefix)) != null)
{
    // prefix found
}


#Tip 382.

If you have a boolean expression that is evaluated very frequently (in a loop, for example), it is usually a good idea to store the result of the expression in a variable. This can improve the performance of your program, because the expression only needs to be evaluated once.


#Tip 383.

you're able to select a data item in a ContentPresenter and instantly display a ContextMenu at that specific location. If you have reached a certain cursor position in a TextBox, you can show a ContextMenu at that specific position. A ContextMenu is the most convenient control you can use in this scenario.
A typical ControlTemplate for a TextBox looks something like:

    <CodeBlock TextWrapping="Wrap" Snippet.LineNumber="


#Tip 384.

change property names when you need to
If you have a class like this:

public class MyClass
{
    public string Name { get; set; }
    public string Address { get; set; }
}


And you need to change the
Name
property to
FirstName
and
LastName
, you can do this:

public class MyClass


#Tip 385.

Knowing how your game will render and perform is crucial to building a good game. Ideally, you want to be able to visualize this while you are working on the game. The built-in Profiler in Unity is a great tool to help with this. Each time you run your game, it will generate a file called 'output_log.txt' in your project's root folder. This file contains all of the information that the profiler collects. You can view this file in a text editor


#Tip 386.

If you want to access a file from the Resources folder in Unity, you can use the following code:

TextAsset textAsset = Resources.Load("myfile");

string fileContents = textAsset.text;


#Tip 387.

If you want to create a GUI button that changes color when the mouse is over it, you can do this by creating a GUIImage object and adding a GUITexture component to it. Then, in the OnGUI() method, you can check if the mouse is over the GUITexture object, and if it is, you can change the color of the GUITexture object accordingly.


#Tip 388.

If you need to generate a random number in C#, you can use the System.Random class.


#Tip 389.

If you want a certain piece of code to run only once, you can use the "singleton" design pattern. This is a design pattern that ensures that only one instance of a class exists at any given time. To do this in Unity, you can use the MonoBehaviour Awake() method.

Awake is called when the script instance is being loaded.

This is a good place to initialize any variables or GameObjects before the game starts. Any code


#Tip 390.

If you want to create a 3D game in Unity, you can use the 3D Game Kit to get started. This kit provides a starting point for creating 3D games, and includes various assets and tutorials to help you get started.


#Tip 391.

As code is added to the codebase, it's a good idea to put it into a subsystem that
doesn't interact with the rest of the code. This makes it easier to reason about the
code and to find bugs.

For example, let's say you're adding a new feature to a C# project. You could put the
new code into a new namespace, or even a new assembly. This way, the rest of the code
base is isolated from the


#Tip 392.

If you have a List of objects, you can use Linq to query it and find all objects that match certain criteria. For example, if you have a List of strings, you can use Linq to find all strings that start with a certain letter.


#Tip 393.

If you modify code that's activated by
MonoBehaviour.Update()
, and during the update you find the object is in a different state from where it started, don't try to run
MonoBehaviour.Update()
again.  Unless your object is stateless, or it has identical states, you might do bad things by doing that.
Update() is used by Unity to orchestrate events.  It shouldn't be


#Tip 394.

If you need to create a unique identifier, you can use the Guid class.


#Tip 395.


using
blocks
Be sure to use
using
blocks to automatically clean up your objects.  When you are done with an object and especially one that implements
IDisposable
, you should wrap it in a
using
block:

using (MyClass obj)
{
  ...
}
// obj is automatically disposed here


The
obj


#Tip 396.

If you need to perform an operation on each element of a collection, use a foreach loop.

This is the most efficient way to loop through a collection in C#.


#Tip 397.


if (condition)
{
    action();
}


If you don't need to check the condition, you can use:

else action();


or even

else
{
    action();
}


#Tip 398.

If you need to do something every frame, don't put it in Update, put it in LateUpdate.

This is because Update is called every frame, but LateUpdate is called after all other Update functions have been called. This means that if you need to do something that relies on other Update functions having been called first, LateUpdate is the place to do it.


#Tip 399.

If you want to create an event handler, you can use the EventHandler delegate. This delegate can be used to create an event handler that will be called when an event is raised.


#Tip 400.

Use UnityEvents to trigger events in your code. This is a powerful way to handle communication between different scripts and components in your project.


#Tip 401.

To create a new string in C#, you can use the string constructor. For example:

string myString = new string("Hello, world!");


#Tip 402.

you can use the using statement for things that implement IDisposable. This can be really helpful when you're working with classes that use unmanaged resources, such as file handles and database connections.

The using statement ensures that Dispose is called even if there is an unhandled exception. This is really important, because otherwise your unmanaged resources will leak!

Here's an example:

using (var file = new FileStream("foo.txt", FileMode.Open


#Tip 403.

If you want a enemy to shoot right when it spawns on the scene you can just add this code in its script

public Enemy enemy;
public float delay;


    void Start(){
      Invoke("spawn", delay);
    }

    void spawn(){
     Instantiate(enemy,transform.position,transform.rotation);
    }


Update:

public Enemy enemy;
public float delay;


#Tip 404.

http://derekedede.blogspot.in/2011/12/extending-linq-with-getcomponent.html
I use this often and it's been a huge help for me.


#Tip 405.

Public class example : MonoBehaviour {

// The SerializeField attribute lets you access private fields in the inspector
[SerializeField] private int _example;

}


#Tip 406.

When working with Unity, it is often useful to have a "master" GameObject that controls the overall game. This GameObject can be used to manage game state, load and unload levels, and so on.

One way to structure this is to have a GameManager script attached to the master GameObject. This script can be used to handle all the high-level game logic. Then, have other scripts attached to other GameObjects in the scene that handle more specific


#Tip 407.

in your extension method implementation when you provide
this SomeType parameter
, use
parameter.ToString()
not
this.ToString()
.
This'll work:

  namespace SomeNamespace
  {
    public static class MyExtensions
    {
        public static string ToSaving(this TheType _theInstance)
        {
            return _theInstance.ToString();


#Tip 408.

If you need to debug your code, you can use the "Debug" class. This class provides static methods for printing out information about the current state of your code. This can be helpful for understanding what is happening in your code, and can also be a useful tool for finding bugs.


#Tip 409.

Put this extends script on objects you would like scripted to have targeted collision inputs like bullets.

public class TargetedTrigger : MonoBehaviour {

    public delegate void ColliderAction();
    public ColliderActioninsideCollider;
    public ColliderActionoutsideCollider;
    void OnTriggerEnter(Collider other) { if (insideCollider != null) insideCollider(); }
    void OnTriggerStay(Collider other) { }
    void


#Tip 410.

If you have a string, you can use the String.Format method to insert values into it.

Here's an example:

string s = "The value is {0}";

Console.WriteLine(String.Format(s, 5));

This would output "The value is 5".


#Tip 411.

With Unity, there is a very useful object called Input.
Chapter 8 in your textbook shows how you can use the Input object to do things like check if a certain key was pressed, check if the mouse was clicked, etc.
In this chapter, there is also a section called "Using the keyboard" which shows how you can use Input to detect when certain keys are pressed.

One thing you can do with this is make a script that detects when the "Space" key


#Tip 412.

If you need to perform an operation on a large number of objects, it is often more efficient to use a for loop rather than a foreach loop. This is because a for loop uses an indexer, which is faster than the iterator used by a foreach loop.


#Tip 413.

Consider using the Select extension method to perform a transformation on a sequence of items. This is especially useful when you want to transform a sequence of objects into a sequence of different objects.

For example, suppose you have a sequence of Person objects and you want to transform it into a sequence of PersonViewModel objects. You could do this with the following code:

var personViewModels = people.Select(p => new PersonViewModel { Person = p });


#Tip 414.

Do not use the Application.loadLevel() function to change between scenes from code. The well-known problem is that Application.loadLevel() only works as expected when using Unity's default startup scene. Trying to call it from a scene you've added or loaded manually will cause memory leaks, or worse, crash Unity.


#Tip 415.

Let's say you have these variables declared

Vector3 pos;
float width;
float height;
int shape;

IEnumerator PosHashChangeDelay()
{
    while(true)
    {
        poshash = pos + Mathf.Pow(width, shape) * new Vector3(Mathf.Sin(Time.time*4), Mathf.Sin(Time.time*4), Mathf.Cos


#Tip 416.

If you find yourself frequently writing code that looks like this:

if (someCondition) { // do something }

then you can use the null coalescing operator (??) to simplify your code:

// equivalent to the code above someValue = someCondition ? someValue : null;

This is especially useful when you need to check for null values before performing an operation:

someValue = someValue ?? "defaultValue";


#Tip 417.

If you want to create a game with realistic graphics, you can use the Unity 3D engine. This engine is able to create photo-realistic images and simulations.


#Tip 418.

One tip for working in Unity 3D is to make sure that you keep your scene well organized. This means creating folders for different types of assets, and labeling them clearly. This will make it easier to find what you need later, and will also help keep your project files organized.


#Tip 419.

</b>
If you want to analyze a string to see if it contains a valid number, you can use the
Double.TryParse()
method. This method tries to convert the string to a double, and returns
true
if it succeeds or
false
if it fails. For example:

string s = "1234";

if (Double.TryParse(s, out


#Tip 420.

Don't use repeated code blocks.

This is generally good advice for any programming language. Repeating code can lead to errors, and makes your code harder to read and maintain.


#Tip 421.

If you need to represent a sequence of characters that may contain any Unicode character, you can use a String object.


#Tip 422.

when you need to get a Maze Game object, use

GameObject.FindWithTag("Maze");

instead of

GameObject.Find("Maze");

The reason for this is that "Maze" is not the name of the Maze Game object. The name of the Maze Game object is actually "Maze(Clone)". "Maze" is just its prefab name. So if you use GameObject.Find("Maze"), you


#Tip 423.

Build a console app with the C# template in Visual Studio, which automates much of the set up for you. The project will come with a predefined
Main
method that you can expand on.

class Program
{
  static void Main(string[] args)
  {
    // do something here
  }
}


If you don't have Visual Studio, you can also use Visual Studio Code and


#Tip 424.

If a type has a method with a
public string this[int index] { get; }
signature for indexing that type, then that type can be used as the value for a
Dictionary<int, string> without any additional work:

Dictionary<int, string> dict = new Dictionary<int, string>();

// The following line adds an entry to the dictionary, using the MyType instance's
// indexer to specify the key and


#Tip 425.

You can use LINQ to query data from a database.


#Tip 426.

If you need to check if a GameObject has a specific component attached to it, you can use the GetComponent function.

However, checking if a GameObject has a specific component attached to it every frame can be expensive. A better way to do it is to cache the result of the GetComponent call in a variable.

Here's an example:

void Update() { // Cache the result of the GetComponent call in a variable. var myComponent = Get


#Tip 427.

Will lets Linq to say that records that should be equal to each other should be considered the same object by the Linq
Producer (in the type of it's key) when performing a Join or Union by call. This way, you can use Joins (and Union) on Entity Framework
entities that have associations to each other.
In your example, you simply need to specify an equivelance comparer so that the two ProductLevels in each ApplicationCompare are


#Tip 428.

In C#, it is considered good practice to use the using statement to automatically dispose of objects that implement the IDisposable interface.

This ensures that the objects are properly disposed of when they are no longer needed, which can help to avoid memory leaks in your application.


#Tip 429.

If you have a method that returns a bool, you can use it as a condition in an if statement.

For example, consider a method named IsValidInput that takes a string as input and returns true if the string is valid, false otherwise. You can use this method in an if statement like this:

if (IsValidInput("foo"))

{

// input is valid, do something

}

else

{

//


#Tip 430.

In order to make your game more efficient, you can use the profiler tool that is built into Unity. This will help you to see where your game is spending the most time and where you can optimize your code.


#Tip 431.

If you want to create a projectile that fires in a straight line, you can use the Rigidbody.AddForce() method. This will add a force to the rigidbody of the object, causing it to move in the direction you specify.


#Tip 432.

In your program, you might want to create a static class that allows you to put in percentages and have it automatically convert that to a decimal.
This can be especially useful when working with money.
Here's how you could do it:

public static class Percentage
{
    public static decimal ToDecimal(int percent)
    {
        return (decimal)percent / 100;
    }
}


#Tip 433.

+
cs
+string something = "something";
+if (something.length > 5) {
+   something = something.substring(0, 5);
+}
+//result: something
+

+
+*/
+
+// Write your code here
+
+/*
+
+THE TERNARY SERIES PLAYGROUND ---
+
+Exercise 3 of 8
+
+Fill in the bl


#Tip 434.

when you connect a listener to a trigger, deregister it when you're done.
This is important because Unity C# triggers can fire multiple times, and you don't want your listener to be invoked unexpectedly.

Here's an example:

public class MyClass {
    public void OnTriggerEnter(Collider other) {
        // Deregister the listener when we're done.
        other.onTriggerExit.RemoveListener(OnTriggerExit);


#Tip 435.

If you want to make a object move towards another object in Unity 3D, you can use the "Transform.LookAt" method. So for example, if you have an object called "Target" and you want another object called "Mover" to move towards it, you would do this:

Mover.transform.LookAt(Target.transform);

Mover will now rotate to face Target, and then move in that direction.


#Tip 436.

If you need to convert a value from one type to another, you can use the Convert class. For example, if you need to convert a string to an int, you can use the following code:



int i = Convert.ToInt32("5");


#Tip 437.

avoid using arrays as out/ref parameters. There are no compile-time or run-time advantages to using arrays. It's simply a matter of goodp

When you call a C# method with a reference to an array or object, the method accepts its storage location - not its value. The called method can change the data in the object or array, and those changes will be seen by the caller.

This is often seen as an advantage of C# over other languages,


#Tip 438.

If you need to find an object in 3D space, you can use the Raycast command. This will return the first object that the ray hits.


#Tip 439.

If you want to create a more realistic environment, you can use Unity's Post Processing Stack. This stack can help you add effects like depth of field, ambient occlusion, and color grading to your scene.


#Tip 440.

There's a handy trick you can use to check if a given string contains a particular substring. You can use the .Contains() method, which will return true if the substring is found, or false otherwise.

For example, if you have a string called "MyString" and you want to check if it contains the substring "foo", you can use the following code:

if (MyString.Contains("foo"))

{


#Tip 441.

If you want to wait for a certain amount of time in Unity, you can use the Invoke method. This will wait for a specified amount of time before executing a method. For example, if you wanted to wait 2 seconds before executing a method, you would do the following:

Invoke("methodName", 2);


#Tip 442.

You can use the "LineRenderer" component to draw lines in Unity. To use it, first add the component to a GameObject. Then, in the "Points" array, add the positions of the two endpoints of the line you want to draw. The "StartWidth" and "EndWidth" properties control the thickness of the line.


#Tip 443.

If you're checking a bool and multiple cases, use the logical or operator instead of the is keyword.

This can help you shortened your code. For example, if you're checking if a bool is true or false, you can use the is keyword like this:

if (isTrue || isFalse) { // Do something }

However, you can also use the logical or operator:

if (true || false) { // Do something }

Both of


#Tip 444.

If you want to show or hide a GameObject, you can use the GameObject.SetActive() method. For example, if you have a GameObject named "myObject" and you want to hide it, you would use this code:

myObject.SetActive(false);


#Tip 445.

If you have a method that you only ever want to call once, you can use the UnityEvent class to do this.

Here's an example:

public class MyClass : MonoBehaviour { public UnityEvent onStart; // ... void Start() { onStart.Invoke(); } }


#Tip 446.

If you want to create a smooth camera movement in Unity 3D, you can use the following code:

Camera cam = Camera.main;

float speed = 0.1f;

Vector3 targetPos = transform.position + Vector3.forward * 10;

cam.transform.position = Vector3.Lerp(transform.position, targetPos, speed);


#Tip 447.

http://www.dofactory.com/Patterns/PatternObserver.aspx#_self2


#Tip 448.

If you want to generate a random number, you can use the UnityEngine.Random.Range() method. For example, the following code will generate a random number between 1 and 10:

int randomNumber = UnityEngine.Random.Range(1, 10);


#Tip 449.

Suppose you have a
List<Foo>

list
that you're talking about, but there's no Task, blocking, etc.  Suppose you want to figure out if there's a unit that has health < 100.  Here's how you can do it:

bool result = list.Any(foo => foo.Health < 100);


#Tip 450.

If you want to create a 3D object that can be interacted with by the user, you can use the Unity 3D Toolkit. This toolkit provides a set of tools that allows you to create 3D objects that can be interacted with by the user.


#Tip 451.

If you want to create a textured 3D model, you can use the Unity 3D editor to create your model, then export it as an .OBJ file. Then, you can use a 3D modeling program to apply textures to your model and export it as a .3DS or .OBJ file.


#Tip 452.

When working with data structures and collections, LINQ is a great way to manage and query your data. You can learn more about LINQ here:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/


#Tip 453.

If you want to create a custom cursor for your game, you can do so by creating a new Sprite and setting its Pivot property to (0.5, 0.5). Then, you can position this Sprite at the position of your mouse cursor.


#Tip 454.

If you want to check if a certain key is pressed, you can use the Input.GetKey() method. For example,

if (Input.GetKey(KeyCode.Escape))

{

// do something

}


#Tip 455.

add a GameObject with a BoxCollider2D and custom script that looks like this:

public class BackgroundController : MonoBehaviour { public GameObject nextBackground; // Use this for initialization void Start () { } // Update is called once per framevoid Update () { } void OnTriggerExit2D(Collider2D other) { if(other.transform. gameObject] == Player) nextBackground.SetActive(true); Destroy(gameObject); } }


#Tip 456.


var badAmounts =
  IEnumerable<decimal>
  methodAddingList()
  .Where (x => Decimal.Compare(x, underThreshold) == -1)
  .OrderByDescending (x => x);


It saves having to do an if statement in your iterating loop and it gives you an ordered list(?) giving you the opportunity


#Tip 457.

You can create extension methods for types that you don't control! This can be really handy for adding functionality to types in the .NET Framework, or to third-party types.


#Tip 458.

Unity has a great feature called "Asset Bundles" which allows you to package up game assets into separate files. This is really useful if you have a lot of large assets, or if you want to update your game without having to re-download the entire thing.



To use asset bundles, first you need to create a new "AssetBundle" folder in your Assets directory. Then, select the assets you want to include in the bundle and drag them into the


#Tip 459.

Change public variables to properties.

Here's why: Public variables can be changed by any code in your program. This can lead to hard-to-find bugs.

Properties can be marked as read-only or write-only. This makes it clear what code is allowed to change the value of the property.


#Tip 460.

If you want to change the value of a public variable in another script, you can use the following code:



OtherScript.publicVariable = newValue;


#Tip 461.

Linq can't be used for data that's being modified by the Event System in a loop, but there's a workaround for this. Instead of using linq, you can use the "Select" method of the Event System's base event data class. This gives you access to the raw data that's being stored in the event, and you can modify it without having to use linq.


#Tip 462.

Function that initializes an array:

public int[] initializeArray() { int [] array = new int [10]; for (int i = 0; i < array.Length; i++) { array[i] = i * 2; } return array; }

To use this function, simply call it like this:

int[] myArray = initializeArray();


#Tip 463.

If you want to run a method in a separate thread, you can use the Thread class. For example:

Thread myThread = new Thread(new ThreadStart(MyMethod));
myThread.Start();


#Tip 464.

<blockquote>
<p>You can use the "as" operator to cast one type to another. For example:</p>
<pre>
<code>string s = "hello";
object o = s;
int i = o as int? ?? 0;
Console.WriteLine(i); // prints 0
</code>
</pre>
</blockquote>


#Tip 465.

Don't return objects from invalid states.
This is generally a good idea for any programming language, but C# is strict about types and allows you to easily create contracts with the compiler. So if your class is in an invalid state, don't return it from any public methods.

public class MyClass
{
    private int _value;

    public MyClass(int value)
    {
        _value = value;
    }

    public static MyClass


#Tip 466.

In C#, you can use the "as" keyword to convert between types. For example, you can convert a string to an int like this:

int i = "5" as int;


#Tip 467.

If you have a MonoBehaviour-derived class that needs to do some work every frame, don't use Update().  Instead, override the MonoBehaviour.OnAnimatorIK() method.  OnAnimatorIK() is called automatically by the Animator component every frame, so you don't need to do anything special to call it.

The Update() method is called every frame regardless of whether or not the game object is active, so if your game object is inactive


#Tip 468.

If you want to expand an IEnumerable if it is not null, you can use the following code:

IEnumerable<SomeType> GetAllSomeTypes() {
    var fromData = dm.GetAllSomeTypes();
    return fromData == null ? Enumerable.Empty<SomeType>() : fromData;
}


This works by checking if the data returned from Get


#Tip 469.

If you want
n
'workers' to run, start
n
number of tasks and
WaitForAll()
on the returned
Task[]
from
ToArray()

For example:

public Task[] WriteValuesToDb(IEnumerable<int> values, int numWorkers)
{
        var workers


#Tip 470.

If you want to make a 2D game in Unity, you should use the SpriteRenderer component instead of the MeshRenderer component.


#Tip 471.

You can use the "Time.deltaTime" variable to get the amount of time that has passed since the last frame. This can be useful for things like moving objects over time.


#Tip 472.

If you want to quickly create a new Unity project, you can use the Unity Hub application. This will allow you to create and manage multiple Unity projects from a single location.


#Tip 473.

When working with the string class, you can use the String.Format() method to insert variables into a string template. This can be useful when creating messages or output to be displayed to the user.

Here's an example:

string name = "John";

Console.WriteLine(String.Format("Hello, {0}!", name));

// Output: "Hello, John!"


#Tip 474.

If you're working on a 2D game in Unity, you can easily add a background image by using a SpriteRenderer component. Just select your image in the Assets window, drag it onto the Scene view, and change the Sprite Mode to "Sliced" in the Inspector.


#Tip 475.

To create a new string you can use the StringBuilder class.


#Tip 476.

Whenever you have a reference to an object that you're not sure is going to be valid, check it for null before using it.

For example, let's say you have a reference to a GameObject called "player":

GameObject player;

Before using the "player" object, you should check to see if it's valid:

if (player != null) { // do something with the player object }


#Tip 477.

Now that we can notice when our device connectivity changes using the
NetworkInformation
namespace, we might have a use case for reacting to changes in the connectivity type as they happen. For example, if the user is playing a game that uses the internet and the phone is switched to airplane mode, maybe there's a notification that can be displayed to the user.
We can use the
NetworkInformation.NetworkStatusChanged
event to be notified when the


#Tip 478.

You can use the String.Format method to insert variables into a string. For example, if you have a string that looks like this:



var message = "Hello, {0}! Welcome to our website.";

You can use String.Format to insert a variable into that string, like this:



string.Format(message, "John");

This would result in the string "Hello, John! Welcome to our website."


#Tip 479.

try to use IComparable and IComparable<T> when possible. By using the more specific version, you can avoid having to create an implementation using the object.Equals() method. Here's an example from the project management software suite from Trac:


#Tip 480.

// Get the position of the mouse cursor on the screen
Vector3 mousePosition = Input.mousePosition;

// ...or in world coordinates
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);


#Tip 481.

http://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html
Scene Management


#Tip 482.

Independently of whatever solution you do for this, you should also try to move your messaging outside the update cycle.
Change your
shoot
class to inherit from a message class, then have a
Iterator
or similar,
poll()
all messages from a queue and handle accordingly, immediately.
This will make sure the manager-class can always stay up to date and does not have to wait for the next message


#Tip 483.

You can use the String.Join method to concatenate strings together.


#Tip 484.

// Using a multiple liner if statement to do different actions depending on a variable
        {
            if (Input.GetKeyDown(KeyCode.LeftArrow))
            {                                                   // you can use both && and ||, just remember they have precidence,
                                                                // so this statement means, if the left and right keys are both down,
                print("left arrow is held down");                // THEN the left key is pressed before


#Tip 485.

Achieving enum type safety

If you're working with enum types in C#, you can use the Enum class to make your code more type-safe. For example, let's say you have an enum type with the following values:

public enum MyEnum
{
    Value1,
    Value2,
    Value3
}

If you want to make sure that only values from the enum are used, you can use the Enum.


#Tip 486.

+
+When you want to create an object that represents some sort of data structure, it is often a good idea to create a class to represent that data structure. For example, if you wanted to create a class to represent a linked list, you might create a LinkedList class with methods to add and remove items from the list, and properties to access the data in the list.


#Tip 487.

If you need to create a copy of an object, you can use the MemberwiseClone() method. This method will create a shallow copy of the object, which means that it will copy the values of the object's fields.


#Tip 488.

If you want to do something when a button is pressed, you can use the OnClick() event. For example, if you have a button named "MyButton", you can do this:

MyButton.onClick.AddListener(() => {
    // Do something when the button is pressed
});


#Tip 489.

you can use || instead of if to make code much cleaner
Please do not use the || operator in an if statement. The correct way to use it is in a boolean expression, like this:

bool someCondition = foo || bar;

if (someCondition)
{
    // do something
}


#Tip 490.

You can use the C# yield keyword to add pause points in your code. This can be useful for waiting for an animation to finish playing, or for waiting for a user to input some data.

To use yield, you first need to create an IEnumerator function. Inside this function, you can use the yield keyword to specify when you want the code to pause. For example:

IEnumerator Example() { //Do something Debug.Log("Do


#Tip 491.

PublicFieldModifiers.

    public class QuickTip
    {
        public static void Main()
        {
            string firstName = "John";
            string lastName = "Doe";

            // The following line would throw an error because the field is read-only.
            // firstName = "Jane";

            // The following line would also throw an error because the field is read-only.
            // lastName.Substring(2);


#Tip 492.

ignore component-level State Management (which is the most common form of state management in Unity) and favor using Scriptable Objects.

If you have a complex GameObject with many different components, it can be difficult to keep track of the state of all those components. A better approach is to use Scriptable Objects to store the state of your GameObjects. This way, you can easily access the state of the GameObjects from anywhere in your code, and you don't have


#Tip 493.

If you want to create a more realistic lighting effect in your game, try using light cookies. Light cookies are images that are placed on light objects and emit light in a specific pattern. This can create a more believable lighting effect in your game, and can also help add more interest to your levels.


#Tip 494.

If you want to perform an action on a sequence of items, it is often more efficient to use the for each loop rather than a standard for loop.


#Tip 495.

If you want to do something when the player collides with an object, you can use the OnCollisionEnter method.


#Tip 496.


public static class UnityBox
{

    // default chat color
    public static string DefaultColor = "FFFFFFFF";

    public static string Chat(string message, string chatColor = DefaultColor)
    {
        return string.Format("<color=#" + chatColor + ">{0}</color>", message);
    }

    public static string ChatLink(string message, int entity


#Tip 497.

// First, define a utility method to get the current class type:

public static Type GetCurrentClassType()

{

StackFrame frame = new StackFrame(1);

MethodBase method = frame.GetMethod();

Type type = method.DeclaringType;

return type;

}

// Then, you can use it like this:

Debug.Log(GetCurrentClassType() + ": MyMethod()


#Tip 498.

To make a GameObject kinematic, navigate to the Rigidbody component attached to the object and check the "Is Kinematic" box. This will make the object not be affected by physics.


#Tip 499.

If a method EndsWith(something), be sure there is a StartWith(something).

That's a great programming pattern tip! Thanks for sharing!


#Tip 500.

If you want to add a little bit of player control to a gameobject, you can add a rigidbody component to it. This will give the gameobject a physical presence in the game world and allow the player to interact with it.


#Tip 501.

If you need to perform an action on all objects of a certain type, you can use the System.Type.GetType() method to get the type, then use the System.Type.IsAssignableFrom() method to check if an object is of that type.

For example, if you wanted to destroy all game objects that are of type "Enemy", you could do the following:

foreach (GameObject go in UnityEngine.SceneManagement.


#Tip 502.

Don't use exceptions to manage the normal flow of your code. Use exceptions only to handle genuine exceptions.
For example:

// Passing multiple values back from a method
// GOOD: return a Tuple<bool, DateTime>
public Tuple<bool, DateTime> TryGetDateTime(string input)
{
    DateTime dt;
    if (DateTime.TryParse(input, out dt))
    {
        return T


#Tip 503.

In your script, use a function B in the same place as function A. When you click A it will activate function B.

void A()
{
    print("A");
}

void B()
{
    print("B");
}


In the editor, you can add a new script component to your object and replace the
Update
function with this:

void Update()


#Tip 504.

If you are working with a List, you can use the Sort() method to sort the list in ascending or descending order.


#Tip 505.

You can use the String.Format method to insert variables into a string.

Here's an example:

string name = "John";
Console.WriteLine(String.Format("Hello, {0}!", name));

This would output "Hello, John!"


#Tip 506.

If a method is going to return an array, you should use
an IEnumerable base class.

This will allow the caller to more easily work with the results of the method.


#Tip 507.

If you have the following expression:

var result = from x in collection where x.Property1 == "Value1" || x.Property2 == "Value2" || ... select x;


Where there are (potentially) hundreds of properties being evaluated and some conjunction of them gaurantee a true result, then you can use Linq async/parallel capabilities to make it run faster:

var result = from x


#Tip 508.

when you're using OnGUI(), you can use Event.current.type to check if the current event is of type EventType.MouseUp, and if it is, you can check which mouse button was pressed with Event.current.button.


#Tip 509.

If you want to create a realistic water effect, you can use a plugin like Advanced Terrain Shaders.


#Tip 510.

If you have a method that you only want to be called from the main thread (Unity's main thread), you can use the [Unity.MainThread] attribute:

[Unity.MainThread] public static void MyMethod() { // Only called from the main thread! }


#Tip 511.

https://answers.unity.com/questions/499405/read-random-lines-from-textfile.html

You can use the StreamReader.ReadLine() method to read random lines from a text file.


#Tip 512.

Never return "null" without a good reason

This is generally considered to be bad practice, as it can lead to unexpected behavior and errors. If a method is supposed to return an object, then it should return a valid object instance, or an exception should be thrown if something goes wrong. Returning null should only be done in special cases where it is truly expected and handled by the calling code.


#Tip 513.

If you want to find out if a list of objects contains a specific object, you can use the Any() method. For example:

var list = new List<GameObject>() { gameObject1, gameObject2, gameObject3 };

if (list.Any(x => x == gameObject2))
{
    // do something
}


#Tip 514.

When you need to know a directory or file name, but you don't need to use it, don't load it into a string variable. Instead, use the built-in classes Path and DirectoryInfo to load the path but not have a full string variable for it.
Here's an example:

DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\Me\folder1\folder2\folder3");


#Tip 515.

Instead of doing this:

if(magicNumber == 5 && cool == true) {
  // run some the best code ever written.
}


Do this:

if(magicNumber == 5) {
  if(cool == true) {
   // run some the best code ever written.
  }
}


#Tip 516.

You can create a "scriptable object" to store all the data for your level, and then write a script to load/save it as an asset.
This will allow you to manage your level data in a central place, andjson


#Tip 517.

If you want to create a procedural sky, you can use a skybox. A skybox is a cube with six faces, each of which is a texture. The six faces correspond to the six faces of a cube, which are the positive and negative x, y, and z faces.

To create a skybox, first create a cube in Unity 3D. Then, assign the six faces of the cube to six different textures. In the Inspector, under the Meshes tab,


#Tip 518.

If you want to create a more immersive experience for your players, you can add some environmental sounds to your game. This can help create a more realistic and believable world for your players to explore. You can find a variety of free sound effects online, or you can create your own.


#Tip 519.

make your next programming project as a side project. Commit to eight or ten minutes a day on it. Driven by a simple process of elimination, you will have left the project completely in a month.

There are several reasons why this is a good tip:

1. It's a great way to learn a new technology or language.

2. It's a great way to keep your programming skills sharp.

3. It's a great way to get some new


#Tip 520.

If you want to interpose handlers for events in a chain where you cannot modify the existing chain, simply
implement your own callback, delegate it to the original callback, then subscribe your handler to the
interposed callback.
For example:

class Handler
{
  private EventHandler _fancyEventHandler;

  public Handler()
  {
    _fancyEventHandler = ( sender, e ) =>


#Tip 521.

To create a multiline string in C#, you can use the @ symbol before the start of the string. For example:

string s = @"This is a

multiline string";


#Tip 522.

You can use the null coalescing operator (??) to provide a default value for a nullable value type. For example, if you have a nullable int variable that may contain a null value, you can use the following code to assign a default value of 0 if the variable is null:

int? someValue = null;
int defaultValue = 0;
int value = someValue ?? defaultValue;


#Tip 523.

If a variable is only used for checking for a value in an if statement, you can use the immediate assignment operator `=` within the if statement.

Here's an example:


csharp
if (something = true)
{
    // do something
}



This is functionally equivalent to:


csharp
if (true == something)
{
    // do something
}


#Tip 524.

If you want to create a new script in Unity, go to the "Project" window and click the "Create" button. Then, select "New Script" from the drop-down menu.


#Tip 525.

When you have a class that holds a reference to another object, always make the class implement the IDisposable interface. This will ensure that the held object is properly disposed of when the containing class is disposed.


#Tip 526.

In Unity you can have a MonoBehavior access other non-MonoBehavior classes by declaring them explicitly.

public class Pickup : MonoBehavior {
    public ScoreController scoreController;
    void OnTriggerEnter () {
        scoreController.addScore(10);
    }
}


By declaring the object like this, you can set it in the Inspector, so you don't need to look up other objects with <


#Tip 527.

If you want to create a custom inspector for a script, you can create an editor script.Editor scripts are scripts that allow you to customize the Unity editor.

To create an editor script, create a new C# script and open it in your editor of choice. Then, add the following code:

using UnityEditor;

[CustomEditor(typeof(MyScript))]

public class MyScriptEditor : Editor

{

public override void


#Tip 528.

If you want to create a new Unity project from scratch, it's always best to start with the Default Project Template. This will give you a bare-bones project that you can then build upon.


#Tip 529.

"find the smallest non-zero positive number in an int array"

Here's one way to do it:

int[] numbers = {4, 0, 2, 6, 0, 1, 3, 5, 7};

int smallest = numbers.Where(n => n > 0).Min();

Console.WriteLine(smallest); //prints "1"


#Tip 530.

If you find yourself frequently checking a variable to see if it is equal to some specific value, it is usually a good idea to convert that variable into an enum. This can make your code more readable and easier to maintain.


#Tip 531.

If you want to create a list of items that you can manipulate (add, remove, etc.), you can use the List<> class.


#Tip 532.

If you need to know if a string contains a certain substring, you can use the IndexOf method. For example, if you need to know if the string "Hello world" contains the word "world", you can use the following code:

if ("Hello world".IndexOf("world") != -1) {
    // The word "world" was found
}


#Tip 533.

Try to make as many members of a class "private" as possible. Only make them public when necessary.

The main reason for this is that it makes your code more maintainable and easier to understand. When a member is private, it's clear that it can only be accessed by code within the same class. This makes it much easier to reason about the code and figure out how it works.

Of course, there are exceptions to this rule. In some cases, you may


#Tip 534.

var foo = new List<Foo>();

foreach(var f in foo)

{

DoSomethingWithFoo(f);

}

This is called the "iterator block" pattern. It's a good way to iterate over a collection and perform some action on each element.


#Tip 535.

There's a native C# method called
IsNullOrWhiteSpace
that you can use.

var isStringNullOrBlank = string.IsNullOrWhiteSpace("");


#Tip 536.

you can override a property in a derived class by setting the access modifier of the derived property to the access modifier of the base property, or less restrictive. For example, if you want to create a new derived property that overrides the base property GetAge(), you can set the access modifier of the derived property to "protected" while keeping the base property modulation to "public".

This pattern can be useful when you want to create a property in a derived class that has different behavior than the


#Tip 537.

If you want to find a substring in a string, you can use the IndexOf method. For example, if you have the following string:

    string myString = "This is a test string";

And you want to find the index of the substring "test", you can use the following code:

    int index = myString.IndexOf("test");

This will give you the index of the start of the substring "test", which


#Tip 538.

If you want to ensure that a certain piece of code is only executed once, you can use the lazy initialization pattern. This pattern uses a delegate to initialize a field only when it is first accessed.

To use the lazy initialization pattern, you first need to create a delegate that wraps the initialization code. The delegate should have a return type and accept no parameters. Next, you create a private field that is of the same type as the delegate's return type. Finally, you create


#Tip 539.

If you ever have to have a game of some sort, where the camera is always pointed to the player, you can use this code to make it always look at the player.

public class CameraFollow : MonoBehaviour {

public Transform target;

void FixedUpdate () {
    // Follow the player if there is one
    if (target) {
        transform.position = new Vector3(target.position.x, target.position.


#Tip 540.

In the Animation window, you can hold Shift and left-click on multiple keyframes to select them all. Then you can move them all at once or change their values all at once.


#Tip 541.

If you want to create a smooth transition between two images, you can use a "lerp" function. To do this, you'll need to use the UnityEngine.Mathf namespace.

Mathf.Lerp(a, b, t) will transition from image a to image b by a certain amount t. t should be a value from 0 to 1, where 0 is a, and 1 is b.


#Tip 542.

If you want to have a custom Inspector for your script, you can create a class that inherits from Editor and override the OnInspectorGUI() method.


#Tip 543.

If you want to create a new object and assign it to a variable, you can use the "new" keyword, like this:

MyClass myObject = new MyClass();


#Tip 544.

+
+If you ever need to call a function on a GameObject and you're not sure if it exists, you can use the Unity "Safe" methods. For example, if you need to call the function "DoSomething" on a GameObject named "MyGameObject", you can use the following code:
+
+

+if (MyGameObject != null)
+{
+    MyGameObject.DoSomething();
+}


#Tip 545.

Singing something like echo or la (or ny ny or even zoning out) makes tracing and debugging a lot easier.

When you're trying to figure out what's going on in your code, it can be helpful to sing or say something out loud as you trace through the code. This will help you keep your place and make it easier to focus on the code.


#Tip 546.

If you ever need to create a quad that's not axis-aligned, create two triangles instead.

To do this, first create two vertices in the middle of the quad, and then create four more vertices at the corners. Connect the middle vertices together with an edge, and then the four outer vertices together with two edges. Finally, connect the outer vertices together with an edge.


#Tip 547.

If you're working with a string, and you need to call a method on it,

use the StringBuilder class. For example, if you need to call the

ToUpper method on a string, you would do this:



StringBuilder sb = new StringBuilder(myString);

sb.ToUpper();



This is much more efficient than doing this:



myString = myString.ToUpper


#Tip 548.

If you want to make a method that can be called without having an instance of the class, you can make it static.


#Tip 549.

The UnityMessage

Here's the pattern:

public class MyBehaviour : MonoBehaviour { public UnityEvent MyUnityEvent; void Start() { // Subscribe to the event indefinitely. MyUnityEvent.AddListener( HandleMyUnityEvent ); } void HandleMyUnityEvent() { // Handle the event here. } }


#Tip 550.

If you want to create a new Collider component on a GameObject, you can use the "Add Component" button in the Inspector. However, if you want to quickly add a Collider to multiple GameObjects at once, you can use the "Component" menu in the Hierarchy window.

To do this, first select the GameObjects you want to add the Collider to. Then, go to the "Component" menu and select "Physics > Collider." This will


#Tip 551.

// This will output "Hello, world!" to the console Console.WriteLine("Hello, world!");


#Tip 552.

If you want to create a realistic water effect, you can use a script to add a slight ripple effect to the water surfaces in your scene.


#Tip 553.

Always remember to dispose of your objects when you are finished with them! Not doing so can lead to memory leaks and other nasty bugs.


#Tip 554.

A good programming pattern to use when working with C# is the Model-View-Controller (MVC) pattern. This pattern separates the code that handles the data (the model) from the code that handles the user interface (the view), and the code that handles the interactions between the two (the controller). This makes the code easier to understand and maintain.


#Tip 555.

If your code is doing the same thing to a lot of different objects, chances are you can use a loop instead.


#Tip 556.

ArticleHub_dotnet_standard

You can use the standard library to create a custom data type that is strongly typed and can be used to enforce data integrity.

For example, you could use the System.Collections.Generic.HashSet<T> class to create a custom type that represents a set of unique values, where each value is of type T.


#Tip 557.

Whenever you need to perform an action on a large number of objects, it is often more efficient to use a for loop rather than performing the action on each object individually.


#Tip 558.

Adding a Script to your project

1. Go to the Project window.
2. Click the Create button.
3. Select C# Script from the menu.
4. Enter a name for your script in the New Script dialog and click the Create and Open button.
5. The script will open in your default code editor.
6. Write your code in the editor and save the file.
7. The script will be compiled and you will be able to use


#Tip 559.

Cast your object to an interface that you know it supports.

For example, if you have an object that implements the IEnumerable interface, you can cast it to that interface and then use the GetEnumerator method to loop through the object's elements.


#Tip 560.

always name any object variable you create with a coherent, lower case name, followed by a descriptive upper case variable name.

For example,

Transform myTransform;

This way, you can easily distinguish Unity engine provided objects from your own custom objects.


#Tip 561.

If you want to be able to easily convert between different units of measurement, you can use the System.Convert class. For example, if you want to convert between inches and centimeters, you can use the following code:



double inches = 7.5;

double centimeters = System.Convert.ToDouble(inches * 2.54);


#Tip 562.


#Tip 563.

If you want to delete Leading Zeros from a string, you can use the `TrimStart` method:


csharp
string s = "000123";
s = s.TrimStart('0'); // outputs "123"



This can be useful if you want to parse a string as an `int`, but it has Leading Zeros.


#Tip 564.

If you have an
IEnumerator
that looks something like this:

internal IEnumerator SetBarColorRoutine(float colorProportion)
{
    while (true)
    {
        m_renderBarColor.r = colorProportion.Remap(m_moveProportion, 1, 1, 0);
        m_renderBarColor.g = colorProportion.Remap(m_


#Tip 565.

you can use the
SetParent
method to set a GameObject as the parent of another GameObject. This can be useful for organizing your scene hierarchy, or for keeping track of objects that should move together.


#Tip 566.

Read through the C# 101 article on Microsoft Docs to learn the basics of the C# programming language.


#Tip 567.

Make sure your project is set to 3D mode and not 2D mode. This can be done by going to File > Build Settings. In the scene view, select the environment you want to change. In the Inspector, change the Lighting > Scene >Environment Lighting > Mode to Color.


#Tip 568.

If you want a reference to the transform at a specific index in a Transform array you can use this code:

ind = 5; // index of the transform in the list
Transform trans = arrayOfTransforms.ElementAt(ind);


Note that if you have a List you can use
List.ElementAt(ind)
instead of linq
ElementAt(ind)


#Tip 569.

Keeping two collections in sync
If you need to update two collection in sync you can use the Zip Operator like this:

var namesToBeDeleted= new List<Name>();
var idsToBeDeleted= new List<int>();
Chilzens.Zip(PhysicalPersons, (k,l) =>new {k, l}).ToList()
    .ForEach


#Tip 570.

To make your code more readable and maintainable, it is generally a good idea to use comments.

This will help you to document your code, as well as to keep track of what you have changed.


#Tip 571.

do not abuse locks.

Locks are a great tool for protecting data structures from concurrent modification, but they come at a cost. They introduce potential performance bottlenecks and can lead to deadlocks if not used carefully.

Instead of using locks, consider using other concurrency primitives such as the ReaderWriterLockSlim class. This class provides more granular control over concurrent access to data structures and can avoid some of the problems associated with using locks.


#Tip 572.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    namespace ConsoleApplication33
    {
      class Program
      {
        static void Main(string[] args)
        {

          List<int> listOfNumericValues = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8


#Tip 573.

Look through the API, and learn how to work with the existing objects that come with the new API you want to add. This can be very helpful in writing clean code, and will make your API code much easier to read and maintain.


#Tip 574.

When working with the System.Text.StringBuilder type, it can be useful to create a static instance variable that can be used throughout your code. This way, you don't have to keep instantiating a new StringBuilder object every time you want to use it.


#Tip 575.

you can use the
Time.deltaTime
to make something move a set amount every frame. For example, this will make an object move up by 1.5 pixels every frame:

transform.position.y += 1.5 * Time.deltaTime;


#Tip 576.

If you want to learn how to use Unity 3D, a great tip is to go through the official tutorials. These will teach you the basics of the Unity interface and how to use the various features.


#Tip 577.

One way to abstract a client class is to place abstract methods in a base class that clients MUST implement.

This allows you to call the methods from the base class, but the actual implementation occurs in the child classes.

For example, you might have a base class like this:

public abstract class MyBaseClass {
    public abstract void DoSomething();
}

public class MyClass1 : MyBaseClass {
    public override void DoSomething() {


#Tip 578.

If you are working with sprites, you can use the "Sprite Mode" drop-down menu in the Inspector window to control how they are displayed. The "Single" mode will display a single sprite, while the "Multiple" mode will display multiple sprites.


#Tip 579.

If you need to format numbers with decimal places, you can use the String.Format method. For example, if you wanted to format a number with two decimal places, you could use the following code:

double value = 12.3456;

string result = String.Format("{0:0.00}", value);

//result would be "12.35"


#Tip 580.

Use
Mathf.Abs
to find the absolute value of a float like so:

-3.02f = Mathf.Abs(-3.02f)
3.02f = Mathf.Abs(3.02f)


#Tip 581.

If you want to change the color of an object in Unity 3D, you can use the "color" property in the Material section of the Inspector panel.


#Tip 582.

When you need to invoke a method on a Unity UI Thread and you are not on the UI Thread, you can use this pattern:

public void InvokeOnMainThread(Action action) { if (IsInvokingRequired) { BeginInvoke(action); } else { action(); } }


#Tip 583.

If you want to create a game that has realistic graphics, try using the standard shader.


#Tip 584.

Using ScriptableObjects fo


#Tip 585.

If you find your code using the 'new' keyword to create an object in order to access a property, then you're probably doing something wrong.

This pattern is particularly useful when working with object-oriented code. By avoiding the use of the 'new' keyword, you can improve the readability and maintainability of your code.


#Tip 586.

enum MemberType {
  Active = 1,
  Inactive = 2
}
https://www.codeproject.com/Articles/36912/Enums-in-C


#Tip 587.

There's an
InstanceID
field that you can use like this:

int thisObjectId = this.GetInstanceID();
Debug.Log(thisObjectId);


#Tip 588.

If you need to repeat and wait in Unity, here's something called a coroutine. This allows you to do repeat and wait within the main thread.
This allows you to repeat and wait within the main thread.

Here's an example:

IEnumerator WaitAndPrint(float waitTime)
{
    while (true)
    {
        yield return new WaitForSeconds(waitTime);
        print("WaitAndPrint " +


#Tip 589.

If you are accessing a collection - like a List or an Array - from multiple places, and modifying it in different places,  consider using the System.Collections.Concurrent namespace. This will give you access to collections that have been specifically designed to support concurrent operations.


#Tip 590.

You can do multiple where clauses with an OR statement in between by using a series of pipes (|)

where clause1 || clause2 || clause3


#Tip 591.

If you want to create a list of objects, you can use the List<T> class.


#Tip 592.

If you find yourself constantly checking if a given GameObject has a particular component attached to it, it might be a good idea to create a extension method for it. This way, you can simply call "gameObject.HasComponent<T>()" instead of having to write out the full "gameObject.GetComponent<T>() != null" check.

public static class GameObjectExtensions
{
  public static bool HasComponent<T>(this GameObject


#Tip 593.

You can use the Debug.Log() function to print messages to the console. This can be useful for debugging your code or for giving feedback to the player.


#Tip 594.

In Unity, it is often useful to have a "master" game object that contains all of the other game objects in the scene. This can be helpful for organization and for scripting purposes.

To set this up, simply create an empty game object and name it something like "Master." Then, drag all of the other game objects in the scene into the "Master" object. This will make the "Master" object the parent of all the other objects.

Now,


#Tip 595.


var isObjectActive = gameObject.activeInHierarchy ||
    gameObject.activeSelf ||
    (gameObject.active == true);
if (isObjectActive)
{
   // Do something.
}


#Tip 596.

Use the inspector window to change values in your scene while in play mode. This is especially useful for tweaking things like object placements, lighting, and particle effects.


#Tip 597.

In C#, you can use the String.Format method to insert variables into a string.


#Tip 598.


obstacleTransform.ToList().ForEach(ReverseRotation);

void ReverseRotation(Transform t)
{
    t.localScale = new Vector3(t.localScale.x, t.localScale.y, -t.localScale.z);
}


#Tip 599.

If you want to create a quick and dirty timer, you can use the Stopwatch class. For example:

Stopwatch timer = new Stopwatch();

timer.Start();

// do something

timer.Stop();

long elapsed = timer.ElapsedMilliseconds;


#Tip 600.

If you want to improve the performance of your game, you can try using the Low-Poly environment assets. These assets are designed to be used in low-polygon graphics settings, and can help improve the performance of your game.


#Tip 601.

If you want to create a door that opens and closes, you can use a light to trigger the opening and closing animation. Place a light at the door's hinge, and when the door is opened, the light will turn on and trigger the opening animation. When the door is closed, the light will turn off and trigger the closing animation.


#Tip 602.

If you use
GetComponent<ZeoGameDataProvider>()
in your MonoBehaviour, it will return a ZeoGameDataProvider component.


#Tip 603.

When working with the System.Diagnostics.Process class, it is recommended to use the using statement. This ensures that the process is properly disposed when it is no longer needed.


#Tip 604.

When working with collections, always prefer the LINQ extension methods over the traditional looping constructs. The LINQ methods are more efficient and often more readable.


#Tip 605.

The following is a way to use a
using statement with a variable:

using (var variable = new Variable())
{
    // Statements here
}


#Tip 606.

- Use the "Take" operator to take the first "x" number of elements from a sequence.

- Use the "Skip" operator to skip the first "x" number of elements from a sequence and return the remaining elements.

- Use the "First" operator to return the first element of a sequence.

- Use the "Last" operator to return the last element of a sequence.


#Tip 607.

In general, try to avoid using "magic strings" (i.e. strings that are hard-coded into your code without being given a specific meaning).

Instead, try to use constants or enums for these values. That way, if the underlying value changes, you only have to change it in one place.


#Tip 608.

If you need to perform an action on each element in a collection, it is usually more efficient to use a for loop rather than foreach.


#Tip 609.

the syntax for
as
casts is as follows:

Car myCar = myObject as Car;

if (myCar != null)
{
    // Do stuff with myCar.
}


#Tip 610.

A good programming pattern for handling nullable types in C# is to use the ?? operator to provide a default value if the nullable type is null, as shown in the following code example:

int? x = null;
int y = x ?? 0; // y will be 0 if x is null


#Tip 611.

If you want to create a new object in Unity 3D, you can use the "GameObject->Create Other" menu. This will bring up a dialog with a number of different object types that you can create, including 3D models, lights, and cameras.


#Tip 612.

When you have a number of objects of the same kind and you want to show a different part of them based on a state you have (eg. health) you can use Object Pooling. You can read more about it here: http://bitoftech.net/2015/01/01/introducing-object-pooling-in-unity3d/


#Tip 613.

If you want to quickly create a console application in C#, you can use the "csc" command. For example, if you wanted to create a program called "MyProgram.exe", you could type the following into a text editor and save it as "MyProgram.cs":



using System;

class MyProgram

{

static void Main(string[] args)

{

Console.WriteLine("Hello, world!");


#Tip 614.

The using statement is a C# construct which lets you specify
that a particular object should be automatically disposed when
the using block is exited. This is especially useful for objects
which implement the IDisposable interface, such as the
SqlConnection object.

Here's an example:

using (SqlConnection conn = new SqlConnection("connection string"))
{
    // use the conn object
}

The using statement will automatically call the


#Tip 615.

If you want to improve the performance of your Unity 3D project, you can use the "Optimize Game Objects" feature in the Unity Editor. This will automatically optimize the game objects in your scene and improve performance.


#Tip 616.

If you want to randomly generate a number within a certain range, you can use the Random.Range() method.

For example, if you wanted to generate a random number between 1 and 10, you could use the following code:

int randNum = Random.Range(1, 10);


#Tip 617.

If you have a public variable that you want other scripts to be able to access, but don't want it to appear in the Inspector, you can use the [HideInInspector] attribute. For example:

[HideInInspector] public int myHiddenInt;


#Tip 618.

1) In the Hierarchy, click on Create->3D Object->Sphere

2) With the new Sphere object selected, click on Component->Physics->Rigidbody in the menu bar

3) In the Inspector, check the "Is Kinematic" checkbox

4) Click on the "Add Component" button in the Inspector and add a "Sphere Collider" component

5) In the "Sphere Collider" component, uncheck the


#Tip 619.

apply guard statements to your public methods, especially if you're unsure whether you can (or should) return normally.

This way, you can immediately return early if something goes wrong, and avoid executing the rest of the method. This can help you avoid more complicated logic errors, and can make your code more robust and easier to debug.

For example, consider this method which adds two numbers together:

public int Add(int a, int b) { return a + b


#Tip 620.

If you want to create a NavMesh for your scene, go to the "Navigation" tab in the Unity toolbar, then click "Bake". This will create a NavMesh for your scene, which you can then use for pathfinding.


#Tip 621.

Always use
using
statements when working with SQLite. Here's an example:

using System;
using System.Data;
using System.Data.SQLite;

class Program
{
    static void Main(string[] args)
    {
        // The connection string makes sure the SQLite database is copied
        // to the output directory.
        using (SQLiteConnection connection =
                   new SQLiteConnection(


#Tip 622.

In the below example you want to initialize the Notifier property with a new Notifier(this) only when there is no existing Notifier property:

private Notifier _notifier;

public Notifier notifier
{
    get
    {
        if(_notifier == null)
        {
            notifier = new Notifier(this);
        }
        return _notifier;
    }
    set
    {


#Tip 623.

When you want to be able to easily enable and disable certain behaviors in your code, create an [RequireComponent] attribute that can be turned on and off in the Unity Editor.

We use this pattern all the time in Unity code, for example when we want to be able to easily enable and disable certain behaviors in our code, we create an [RequireComponent] attribute that can be turned on and off in the Unity Editor.

To do this, we simply add the


#Tip 624.


// easily replace a character in a string
string myString = "Some string";
myString = myString.Replace('A', 'B');
myString = myString.Replace('B', 'A');


This will translate all the As to Bs and all the Bs to As in your code


#Tip 625.

If you need to reference a static class member within an instance method, you can use the class name as though it were an instance variable. For example, if you have a static class called "Foo" with a static member called "Bar", you can reference it within an instance method of "Foo" like this:

Foo.Bar


#Tip 626.

When working with the System.IO namespace, use the "using" statement to automatically close files when you are finished with them. For example:

using (StreamWriter sw = new StreamWriter("C:\\temp\\test.txt"))

{

sw.WriteLine("This is a test");

}


#Tip 627.

If you want to use a C# library in your project, you can add a reference to it in your project file. To do this, open your project file in a text editor and add a reference to the library as follows:

<ItemGroup>

<Reference Include="MyLibrary">

<HintPath>..\..\MyLibrary.dll</HintPath>

</Reference>

</ItemGroup>


#Tip 628.

If you want to synthesize a new signal by combining two other signals, make object-oriented design your first step. Rather than combining the signals directly, write a new type that encapsulates both signal values, and write the synthesis code in a member function of this new type. This will always be faster than the naive approach of combining always combining signal values, even if you believe in your heart that that these two signals will never change.

This is particularly important for code that will be run


#Tip 629.

public abstract class BaseClass {
    private static int count = 0;
    private int id;

    public BaseClass() {
        id = count++;
    }
}

class DerivedClass : BaseClass {
}

public static void Main(string[] args) {
    BaseClass bc1 = new DerivedClass();
    BaseClass bc2 = new DerivedClass();
    Console.WriteLine(bc1.id);


#Tip 630.

You can use the string.Format() method to insert values into a string.

For example:

string.Format("The answer is {0}", 42);

will insert the value 42 into the string "The answer is {0}".


#Tip 631.

There's a very handy string method called ``Split`` which lets you easily turn a string like this...

    String sentence = "Hello there, how are you doing?";
    
... Into an array of strings, each element being a separate word:

    String[] words = sentence.Split(' ');
    
This is especially useful for parsing.
    
    
# Tip 9: Size of Primitive Types in C#

C# has built-in


#Tip 632.

If you want to get a distinct list of items from a list, you can use the Linq distinct method. For example, if you have a list of integers, you can use the following code to get a distinct list of integers:

var distinctList = list.Distinct();


#Tip 633.

declaration order of fields and properties, know your future.

The general rule of thumb is that fields should be declared before properties, and properties should be declared before methods. This rule ensures that all fields are initialized before any properties are accessed, and all properties are initialized before any methods are called.

However, there are some exceptions to this rule. For example, if a property needs to access a field that hasn't been initialized yet, it's fine to declare the property first. Similarly


#Tip 634.

If you need to perform an operation on a large number of objects, it is often more efficient to use a for loop rather than a foreach loop.


#Tip 635.

if you're handling a keypress and there is a function that you want called a single time when the user first presses the key (e.g. the user wants to open a menu and this is the "OpenMenu" method), you would normally put the following code in an Update loop:

if (Input.GetKeyDown(KeyCode.Escape)) {
    OpenMenu();
}


For efficiency reasons, you could avoid calling this


#Tip 636.

(nest if and else if; early accept/return/break ; Ternary operator if possible )

If you have a series of if and else if statements, it's generally best to nest them so that you can early accept or return as soon as possible. For example, consider the following code:

if (condition1) { // do something if condition1 is true } else if (condition2) { // do something if condition2 is true } else if (


#Tip 637.

I've found it's good to prefer the direct style of programming: that is, rather than call the GetComponent function, instead set the component by... December 12, 2016

VSL2GIS is a computer game designed to teach GIS modelling. It is part of the UK EPSRC funded VSL2 project, headed by UCL. VSL2GIS is built using the Unity game engine, so that it can be played on a... November 28, 2016


#Tip 638.

If you need to format a string in a specific way, you can use the String.Format method. For example, if you need to format a string as a currency value, you can use the String.Format method like this:

string s = String.Format("{0:C}", 123.45);

The above code will format the 123.45 value as a currency string. The result will be "$123.45".


#Tip 639.

If you need to do a quick check to see if a string contains a specific word or phrase, you can use the String.Contains() method. For example:

string input = "Hello world";

if (input.Contains("world"))

{

// do something

}


#Tip 640.

If you need to perform an operation on a large number of objects, it is often more efficient to use a for loop rather than LINQ. This is because LINQ expressions are often compiled to delegate instantiations, which can incur a significant performance overhead.


#Tip 641.

https://www.codeproject.com/Articles/11898/Eight-Queens-Puzzle

Here's a tip for something you can do in Java:

https://www.baeldung.com/java-8-streams


#Tip 642.

+
+
+
+If you have a Unity script that needs to do something repeatedly at regular intervals, you can use the InvokeRepeating() method to set this up.
+
+
+
+For example, let's say you have a script that needs to check for input every 0.5 seconds. You could use InvokeRepeating() to set this up like so:
+
+
+
+void Start()
+
+{


#Tip 643.

If you want to move an object slowly and smoothly, you will probably want to give your code something like this:

void Update () {
    transform.position = Vector3.Lerp(transform.position, targetPosition, 0.05f);
}


This is where you would put your actual code for what you want your object to do.


#Tip 644.

Don't make fields.

The reason is that fields generally tend to encourage bad programming practices, such as accessing data directly without going through an accessor method, or storing data in an uninitialized state.

Instead, prefer properties, which are like methods that can be used to get and set the value of a field.


#Tip 645.

you can create extension methods. These are just normal methods, but you can "attach" them to a type as if they were part of that type.
For example, you could write an extension method to append two strings:

public static class StringExtensions
{
    public static string Append(this string a, string b)
    {
        return a + b;
    }
}


Then you could use


#Tip 646.

If you want to convert a string to all uppercase or all lowercase, you can use the ToUpper() or ToLower() methods.


#Tip 647.

always call .ToString() on System.DateTime values when storing them back to a database. It's a great way to avoid getting unexpected database errors.

This is because the System.DateTime object stores dates and times in a format that is not compatible with most databases. When you call .ToString() on a System.DateTime object, it returns a string in a format that is compatible with most databases.

So, if you have a System.DateTime object


#Tip 648.

Don't abuse the keyword new ! New is good, but not always. Don't be afraid of it. Use it when it makes the most sense.

As with most things, the golden rule is: use it when it's needed. The keyword new is for allocating objects, but that's not all it does; it also calls the constructor and initializes all fields. When you don't need to initialize fields and constructors, you shouldn't use new .

For example


#Tip 649.

A tip for using Unity is to take advantage of the scriptable object asset type. This is a data container that can hold all sorts of information and be easily created and edited within the Unity Editor. Scriptable objects are especially useful for storing game data, such as items, enemies, or level information.


#Tip 650.

You can use Linq to query a list of GameObjects in Unity and get back a list of all the GameObjects that have a specific component attached to them. For example, if you have a list of GameObjects and you want to find all the GameObjects that have a Collider component attached to them, you can use Linq to do that.

Here's the code:

List < GameObject > gameObjects = //get list of Game


#Tip 651.

You can use the GetComponent function to get a reference to a component attached to a GameObject. For example, you can use it to get a reference to a Rigidbody component, like this:

Rigidbody rb = GetComponent<Rigidbody>();


#Tip 652.

If you want to create a double sided mesh in Unity 3D, all you need to do is create two separate meshes, one for the front and one for the back. Then, you can assign each mesh to a different Material. Finally, you need to make sure that the Backface Culling option is disabled in the Material settings.


#Tip 653.

When working with any kind of closure make sure you copy variables into the closure.
This ensures that the closure captures a local copy of the variable that won't be impacted by operations occurring to the original variable.

Here's an example:

int num = 5;

Actionclosure = () =>
{
    Console.WriteLine(num);
};

num = 10;

closure(); // Prints 5


#Tip 654.

If you want to call a function from another script, you can use the following code:

transform.GetComponent<OtherScript>().FunctionName();


#Tip 655.

If you want to quickly create a list of numbers, you can use the Enumerable.Range method. For example, if you want to create a list of numbers from 1 to 10, you can use the following code:



var list = Enumerable.Range(1, 10);


#Tip 656.

If you want to create a custom inspector for a script, you can create an Editor script. This script will be executed when the inspector is opened for the object it is attached to. In this script, you can override the OnInspectorGUI() function to draw your own inspector.


#Tip 657.

Prevent your game from scaling based on screen size by doing:
Screen.SetResolution(640, 480, false);


#Tip 658.

If you want a property or a field to always be non-null, initialize it to
new
as part of its declaration or in the constructor. Then you don't need to
Assert(property != null)
any more because it can't be.
Of course, it's still possible to
null
the field, anyone can do it for any field. I'm talking about avoiding changing it in your own code


#Tip 659.

Set the Default layer to selected in the new object menu.

1. In Unity, go to Edit > Project Settings.
2. In the Inspector, select Tags and Layers.
3. In the Tags and Layers Project Settings, select the Default layer and set it to selected in the new object menu.


#Tip 660.

If you want to create a floating effect for your gameobjects, you can use the "is Trigger" checkbox in the collider component. This will make your collider trigger collisions, meaning that the object will not physically collide with other objects, but will still trigger collisions.


#Tip 661.

</p>

<p>If you ever need to pause your program for a specified amount of time, you can use the <strong>Thread.Sleep</strong> method. For example, the following code will pause the program for 5 seconds:</p>

<pre>
Thread.Sleep(5000);

</pre>


#Tip 662.

If you want to run some code in a new thread, you can use the Thread class. For example, the following code will start a new thread and run the MyMethod method in it:



Thread t = new Thread(MyMethod);

t.Start();


#Tip 663.

you can use wrapping if-statements (like the example above) to restrict access to blocks of code.
Here's how it works:

if (someCondition)
{
    // code in here can only be executed if someCondition is true
}

This is useful if you want to make sure that a certain block of code can only be executed under certain conditions.


#Tip 664.

If you have an unknown amount of items in a one-dimensional array, and you want to see if each of those items match a certain condition, you can do it like this:

int[] array = {5, 2, 1, 6, 8};
int[] array2 = array.Where(x => x > 5).ToArray();


In the previous example, we wanted to know if each of the elements


#Tip 665.

If you have a bunch of related variables that should all be set to the same value, you can use a single setting function to set all of them at once. For example, in a "Player" class you might have the following variables:

public float maxHealth = 100f; public float currentHealth = 100f; public float healthRegenRate = 5f; public float healthRegenDelay = 2f;

You could write a "SetHealth


#Tip 666.

the String.Format function is really handy for representing strings with interpolated values. In particular, it's often used for interpolating numbers (such as for formatting currencies).

Here's an example:

string s = String.Format("I have {0} apples", 5);


#Tip 667.

To create a new script in Unity, go to the "Project" window and click the "Create" button. Then, select "C# Script" from the options.


#Tip 668.

If you want to reverse a string, you can use the String.Reverse method.


#Tip 669.

The
ToLookup
extension method is useful for creating a map of values, i.e. an index by some key. It could be used something like this:

var fooLookup = fooReader.Records.ToLookup( foo => foo.FooID );


After that, you could use
fooLookup
something like this:

int foo


#Tip 670.

if you have a long string and want to
check whether it contains a particular substring, you can use the

IndexOf
method. For example:

int index = myString.IndexOf("substring");
if (index >= 0)
{
    // myString contains the substring "substring" at position index
}


#Tip 671.

In Unity, you can use the transform.TransformDirection method to transform a given direction from local space to world space. This is useful for things like projectile motion, where you need to take into account the rotation of the object when determining the direction of the projectile.


#Tip 672.

If you need to quickly create a Collider without having to create a separate GameObject, you can use the Capsule Collider component. This will allow you to create a Collider that is essentially a cylinder.


#Tip 673.

Clean up any empty child GameObjects when you're done using them, e.g. after destroying an instantiated prefab.
This avoids having dozens of little GameObjects lying around in your scene, cluttering up the Editor.
You can use the Unity GameObject.Destroy() method to do this:

foreach (Transform child in transform)
{
    GameObject.Destroy(child.gameObject);
}


#Tip 674.

If you need to check if a string is null or empty, you can use the following code:

if(string.IsNullOrEmpty(someString))

{

//do something

}


#Tip 675.

when you want certain items in the game world to share certain data, but you don’t want the items in that game world to share other data - or if you even want different items in different game worlds to share different data - you can use the ScriptableObject class.

A ScriptableObject is a data container that you can use to save data in the form of a Unity asset. This is different from a MonoBehaviour, which is a C# script that is attached


#Tip 676.

One common Unity programming pattern is to have a game object with multiple components, each component being responsible for a different task.

For example, you might have a game object that has a sprite renderer component for drawing the object's sprite, and a rigidbody component for managing its physics.

This pattern can be useful for keeping your code organized and making it easy to add or remove functionality from game objects as needed.


#Tip 677.

If you want to add a lot of objects to your scene and don't want to have to position them all individually, you can use the "Instantiate" function. This function allows you to create an instance of an object at a given position and rotation. So, for example, if you have a prefab of a chair, you can use Instantiate to create a new chair at a specific position in your scene.


#Tip 678.

If you want to create a new object in Unity, you can use the Instantiate() method. This method takes a prefab as an argument, and returns a new instance of that prefab.


#Tip 679.

If you need to rotate an object around a specific point, you can use the Transform.RotateAround() method. This method takes a Vector3 as the first parameter, which is the point to rotate around, and a float for the second parameter, which is the amount to rotate in degrees.


#Tip 680.

If you want to create a 3D object at a specific location in the world, you can use the Instantiate() method. This method takes a GameObject as a parameter and creates a copy of it at the specified location.


#Tip 681.

If you want to create a pool of gameobjects, for example for bullets, use the Resource.

The Resource class allows you to load and unload assets on demand. This can be useful if you want to avoid loading assets until they are needed, or if you want to load and unload assets at runtime to conserve memory.

To use the Resource class, first add a Resources folder to your project. Then, add the assets you want to pool to the Resources folder. Finally


#Tip 682.

You can make use of LINQ's OrderBy and ThenBy methods to sort a list of objects by multiple properties. For example, given a list of Person objects:

var people = new List<Person>
{
    new Person { FirstName = "John", LastName = "Doe" },
    new Person { FirstName = "Jane", LastName = "Smith" },
    new Person { FirstName = "John", LastName = "Smith


#Tip 683.

If you need to create a list of unique strings, you can use the HashSet<string> class. This class will automatically remove any duplicates that are added to it.


#Tip 684.

If you have a method that can be called from either Update or FixedUpdate, but not both, use a bool to track which one it's in.

For example:

void Update () { if (!inFixedUpdate) { //Do stuff here } } void FixedUpdate () { inFixedUpdate = true; //Do stuff here inFixedUpdate = false; }

This way, you can be sure that your code will only run in the appropriate Update or Fixed


#Tip 685.

To convert a string to a byte array, you can use the Encoding.UTF8.GetBytes method.


#Tip 686.

If you have a List<SomeObject> and you own an OtherObject that has a property of type List<SomeObject> and you want to filter someCollection through someOtherCollection, you can do this:

myCollection.Where(obj => someOtherCollection.Contains(obj));


#Tip 687.

Look under the Project Windows for the Assets folder. This folder contains all of your game's assets. If you want to add a custom asset, such as a 3D model or a custom script, simply drag and drop it into this folder.


#Tip 688.

If you want to run a certain block of code only once, you can use the "while" loop.


#Tip 689.

If you want to create a new object in Unity, you can use the "GameObject->Create Other" menu item.


#Tip 690.

If you need to convert between System.decimal values and numeric primitive types (double, float, int, long or ulong) or System.String, just use CType to make the conversion.
Here's a good programming pattern tip for C#: If you need to convert between System.decimal values and numeric primitive types (double, float, int, long or ulong) or System.String, just use CType to make the conversion.


#Tip 691.

If you want to create a custom editor for a script in Unity 3D, you can do so by creating a folder called "Editor" in your project's Assets folder. Then, create a script in that folder with the same name as the script you want to create a custom editor for. Finally, decorate the script with the CustomEditor attribute, passing in the type of the script you want to create a custom editor for.


#Tip 692.

If you want to make sure a certain piece of code only runs once, you can use the UnityEngine.Application.loadedLevelName property. This property returns the name of the scene that is currently loaded. So, you can check if the scene has changed and then run your code if it has.

Here's an example:

if ( UnityEngine . Application . loadedLevelName != "My Scene" ) { // This code will only run if the scene has changed


#Tip 693.

pick an image at random



If you have a list of images, you can use the UnityEngine.Random.Range() method to choose one at random.


#Tip 694.

If you need to loop through a collection of items and perform some kind of action on each item, consider using the foreach loop instead of a for loop. The foreach loop is easier to read and less error-prone.


#Tip 695.

If you want to find out if a specific key is being pressed, you can use the "Input.GetKey" function. For example, if you want to know if the "a" key is being pressed, you can use the following code:

if (Input.GetKey(KeyCode.A))
{
    // do something
}


#Tip 696.

When working with the System.Collections.Generic namespace, remember to use the type parameters wisely. For example, when working with the List<T> class, always use the T type parameter to represent the type of data that the list will contain. This will make your code much easier to read and understand.


#Tip 697.

If you want to create a realistic water effect, try using a plugin like Wasser 2.0. This will add realistic waves and ripples to your water, and you can even add things like fish and other underwater creatures.


#Tip 698.

If you find yourself using the same code in multiple places, it's usually a good idea to create a method and call that method from the various places where you need it. This keeps your code DRY (Don't Repeat Yourself).


#Tip 699.

The simplest way to get Script Execution Order working is to create a static GameManager class that inherits from MonoBehaviour and take advantage of the static reference. Then simply set the execution order of theManager in the Project Settings.

public class GameManager : MonoBehaviour {
    // Public static reference available in all scripts
    public static GameManager theManager;

    // Use this for initialization
    void Awake () {
        // Assigning the static


#Tip 700.

You can change the quality settings for your project by going to Edit > Project Settings > Quality. From here, you can change the overall quality level, as well as enable or disable individual quality settings.


#Tip 701.


List<testDTO> inputParams = new List<testDTO>();
inputParams.Add(new testDTO {
                    ParamName = "Firstname",
                    ParamValue = "Tom",
                    ParamRequired = true
                });
inputParams.Add(new testDTO {
                    ParamName = "Lastname",
                    ParamValue = "Sawyer",


#Tip 702.

If you have a method that you need to call frequently, but you don't want it to be called more than once per frame, you can use the 'LateUpdate' method.

This method is called after all Update methods have been called, so you can be sure that your method will only be called once per frame.


#Tip 703.

You can create a class that inherits from the System.Collections.Generic.List<T> class, and then override the Add method. Doing this will allow you to perform custom processing when items are added to the list.


#Tip 704.


StreamReader reader = new StreamReader("file.csv");
List<String[]> list = new List<string[]>();
string line = null;
while((line = reader.ReadLine()) != null) {
    list.Add(line.Split(','));
}


Here's a tip for something you can do in Unity/C#:
There's a really great


#Tip 705.

If you want to test for a specific key pressed, you can use
if(Input.GetKeyDown("a"))
.
If you want it so that the player keeps moving in a certain direction as long as they press a certain key, you could use
if(Input.GetKey("a"))
.
You can easily add more keys to test for by separating them with a comma, so
if(Input.GetKey


#Tip 706.

If you have a list of items that you need to iterate over, consider using the foreach loop instead of a for loop. The foreach loop is easier to read and less error-prone.


#Tip 707.

If you want to add some realism to your game, try using shaders. Shaders can simulate various effects, such as lighting, shadows, and it can even make your game look like it's taking place in a different environment (such as underwater).


#Tip 708.

If you find yourself writing the same code in multiple places, or if you find yourself having to remember to do the same thing in multiple places, consider creating a method to encapsulate that code. This will make your code more readable and maintainable, and it will make it easier to make changes in the future.


#Tip 709.

Never use Awake and Start together in the same script. Awake is called when the script is loaded, and Start is called when the scene is loaded. If you use them together, Awake will be called twice.


#Tip 710.

Try to avoid using magic numbers in your code. A magic number is a hard-coded value that has no logical explanation, such as 42 or -1. These values can be difficult to understand and maintain, and can cause bugs if they are not used correctly.

Instead, try to use constants or variables for these values. This will make your code more readable and maintainable.


#Tip 711.

For every event, feel free to insert multiple event handlers which will perform exactly the same work as the others, but can be handled separately according to the conditions they are being used.


#Tip 712.

For example if you want to want to know if a DataGrid has changed, you can implement the CellValueChanged event:

//...
private void DataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
  //... code to execute when the cell contents have changed
}
//...


The class I talked about is called CellValueChangedEventHandler.


#Tip 713.

If you want to find out if a certain key is being pressed, you can use the Input.GetKey() method. For example, if you want to find out if the "a" key is being pressed, you can use the following code:

Input.GetKey("a");


#Tip 714.

In Unity 3D, you can use the "Line Renderer" component to draw lines in your scene. This can be useful for a number of reasons, such as drawing a path for an object to follow, or drawing a UI element such as a health bar.


#Tip 715.

If you ever need to move an object a precise distance in a given direction, you can use the Unity 3D Physics.MovePosition() method. This method takes in a Vector3 which represents the distance you want to move, and moves the object that distance in the given direction.


#Tip 716.

If you want to work like a method with an array of bytes, but you don't want to change the underlying bytes data source in your C# code, you can use the Bytes class.

Doing so is simple. Just create a Bytes object with your byte data and then use the methods provided by the class to work with the data. For example, you can get the length of the data with the Length property, or you can convert the data to a string with the


#Tip 717.

If you need to rotate an object around a specific point, you can first parent the object to an empty game object, then rotate the parent object.


#Tip 718.

If you want to create a new GameObject in Unity 3D, you can use the "GameObject.CreatePrimitive" function. This function will create a new GameObject with a default Mesh (e.g. a Cube) and Collider.


#Tip 719.

If you need to perform an operation on each element in an array, you can use the foreach loop. This loop iterates through each element in the array and allows you to perform the same operation on each element.


#Tip 720.

By storing data in an object you want to serialize as a field in a script, you can utilize the Unity >> Inspected Object >> Add Component menu to provide an easy way to create and edit the data. The data can be of any type, but in this example, we will let it store the Name, Gender, Age and Nationality of a player from different parts of the world.

Here's the C# code for the component.

public class PlayerData : Mono


#Tip 721.

When you have a number of similar objects, such as a bunch of enemy characters, it can be helpful to use an array to store them. This way you can easily loop through all the enemies and perform the same actions on each of them.


#Tip 722.

If you want to add a force to a rigidbody in a particular direction, you can use the AddForce function. For example, if you have a rigidbody named "myRigidbody" and you want to add a force of 10 in the x-direction, you would use this code:

myRigidbody.AddForce(10, 0, 0);


#Tip 723.

The using statement is a C# keyword which is used to ensure that a resource is disposed of properly. A using statement defines a scope at the end of which an object will be disposed.

For example,

using (FileStream fs = new FileStream("SomeFile.txt", FileMode.Open)) { // Use the FileStream object... }

In this example, when the using block is exited, the Dispose method of the FileStream object will be


#Tip 724.

When working with strings, you can use the String.Format() method to insert values into a string. For example, if you have a string that contains {0}, {1}, {2}, etc., you can use String.Format() to insert values into those spots.


#Tip 725.

use an interface for stuff that might be a `MonoBehaviour` but also might not be. That way you can decouple your logic from those details and you can write…


#Tip 726.

Assuming you have a GameObject "player" with a RigidBody2D "rb" attached to it:



void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag("PickUp"))
    {
        other.gameObject.SetActive(false);
        rb.AddForce(new Vector2(0, 10));
    }
}


#Tip 727.

If you want to create a 3D object that can be rotated and moved around, you can use the Transform tool. To access this tool, select the GameObject menu and then select 3D Object > Cube. This will create a cube that you can then rotate and move using the Transform tool.


#Tip 728.

If you want to create a low-poly effect, try using the "Shader Forge" asset. It's a node-based shader editor that lets you create all kinds of interesting shaders, including ones with a cel-shaded look.


#Tip 729.

If you want to create a 3D object that looks like it is composed of smaller objects, you can use the Detail object painting tool. This tool allows you to paint a detail object onto the surface of another object.


#Tip 730.

When working with the DateTime type in C#, it is often best to use the System.DateTimeOffset type instead. This type provides a more accurate representation of a point in time, and can help to avoid issues with time zones and daylight saving time.


#Tip 731.

If you want to create a 3D game with realistic graphics, you should use Unity's built-in shaders. For example, the Standard shader can create realistic lighting and shadows.


#Tip 732.

If you have a value stored in a string, and you wish to convert it to a long integer, you can use the following:

long.Parse(stringValue);


#Tip 733.

Don't use magic numbers in your code.

A magic number is a value that has no meaning other than the value itself. For example, setting a player's speed to 5 is a magic number because it doesn't mean anything other than " five units per second".

Instead of using magic numbers, it's better to use constants. A constant is a value that is given a name and can be used throughout your code. For example, you could create a constant for the


#Tip 734.

Set the Name property of objects to something more descriptive.

This will help other developers reading your code understand what your objects represent. It will also make it easier for you to reference those objects in your code.


#Tip 735.

If you have a string representing a number, you can use int.Parse() to convert it to a number.

For example, if you have a string representing the number "42", you can convert it to an integer like this:

int number = int.Parse("42");


#Tip 736.

If you want to repeat a certain block of code multiple times, you can use a for loop. For example, if you want to print out the numbers 1 through 10, you would use a for loop like this:

for (int i = 1; i <= 10; i++)
{
    Debug.Log(i);
}


#Tip 737.

To convert a string to a byte array, you can use the System.Text.Encoding.ASCII.GetBytes method. For example:

string s = "Hello world";
byte[] b = System.Text.Encoding.ASCII.GetBytes(s);

You can then convert the byte array back to a string using the System.Text.Encoding.ASCII.GetString method. For example:

byte[] b = //


#Tip 738.

If you want to create a list of objects, you can use the List<> class. For example, if you want to create a list of integers, you can use the following code:

List<int> myList = new List<int>();


#Tip 739.

If you have a gameobject with a rigidbody2D and you want to apply a force to it in a given direction, you can use the AddForce() method. For example, if you have a gameobject named "Player" and you want to apply a force of 10 in the positive x-direction, you would use the following code:


#Tip 740.

You can use the "mouse look" functionality to control the camera. To do this, simply hold down the right mouse button and move the mouse to look around.


#Tip 741.

If you want to create a quick and dirty particle system, you can create a particle system in Prefab Mode. Then, add a circle or squareCollider to your particle system and check the "Collides" checkbox. This will make your particle system collide with objects in your scene.


#Tip 742.

When you need to do this

       spawnTimer -= Time.deltaTime;

        if (spawnTimer > 0f)
        {
            return;
        }

        spawnTimer = spawnIndicatorVsProb.GetRandomProb(rng);


or this

        cooldownTimer -= Time.deltaTime;

        if (cooldownTimer > 0f)
        {


#Tip 743.

If you have a custom class that you want to be able to serialize and deserialize with the Unity editor, you should mark it with the [System.Serializable] attribute.


#Tip 744.

In Unity 3D, you can create a script to control how an object moves. For example, you can create a script that makes an object move forward forever. To do this, you would need to use the "Update" function. The "Update" function runs every frame, so by putting your movement code inside it, your object will move every frame.


#Tip 745.

If you want to create a game with realistic graphics, you should use Unity's high-definition render pipeline. This will give you access to higher quality lighting and shading, as well as allows you to render your game at a higher resolution.


#Tip 746.


new WaitForSeconds(2f)


You can use this in a coroutine:

IEnumerator Start() {
    // Your code here
    yield return new WaitForSeconds(2f);
    // Your code here
}


This is useful when you need to wait a few seconds during execution before doing something else (like spawning a new object).


#Tip 747.

There's a debugger.Log method which lets you print to the Unity console. This is really useful for checking what your code is doing and for finding errors.

To use it, just put Debug.Log("your message here"); in your code wherever you want to print a message.


#Tip 748.

If you have a string, you can convert it to a byte array like this:

byte[] bytes = Encoding.UTF8.GetBytes(str);


#Tip 749.

use coroutines to make things happen over time, instead of using the Update() function. This can be really useful when you want to do things like animate objects, move them around, or change their properties gradually over time.


#Tip 750.

+
+You can use the "using" keyword to automatically dispose of objects that implement the IDisposable interface.
+
+Here's an example:
+
+using (var foo = new Foo())
+{
+    // do something with foo
+}


#Tip 751.

One way to improve the performance of your Unity C# code is to avoid using excessive public variables. When possible, use private variables and expose them through public properties instead. This allows you to control how and when the variables are accessed, which can help improve performance.


#Tip 752.

A powerful pattern for performing actions based on simple criteria often called an expression lambda.

Lambda expressions are basically a concise way of writing anonymous methods. They are very useful when you need to pass a simple function as an argument to another function.

Here's a simple example of a lambda expression that prints out a message:

Console.WriteLine((x => "Hello, world!"));

Here, the lambda expression is equivalent to the following anonymous method:


#Tip 753.

if (obj is IDisposable)
{
    using (obj as IDisposable)
    {
        // Use the object here
    }
}


#Tip 754.

If you want to be able to reference a certain object in your code without adding a public variable for it, you can use the
FindWithTag()
method. For example, if you wanted to be able to reference your player character without adding a public variable to hold a reference to it, you could do this:

// somewhere in your code...
GameObject player = GameObject.FindWithTag("Player");

// then later,


#Tip 755.

If you want to ensure that a piece of code is only ever executed once, you can use the System.Threading.Lazy<T> class.


#Tip 756.

If you want to create a realistic water effect, make sure to use a shader that supports refraction and fresnel reflections. You can find some great shaders on the Unity Asset Store.


#Tip 757.

If you need to do the same thing over and over, create  a class.  Denote what this class will do by its name.  For example,  if you need to call a web service,  create a 'WebServiceConnector'.   If you need to create a file (log),  create a 'FileCreator'.   
Inside this new class,  create code that will cause this class to do what it is supposed to do.  YOU MAY HAVE TO


#Tip 758.

Instead of using a MeshCollider, you can use a compound Collider made up of a BoxCollider and a SphereCollider. This will give you more control over the collision volume and can result in better performance.


#Tip 759.

If you want to create a purchasing system in your game, you can use the UnityEngine.Purchasing namespace. This namespace includes the classes necessary to create and manage in-app purchases in your game.


#Tip 760.

If you find yourself repeatedly writing the same piece of code, it's a good candidate for a method. By creating a method, you can write the code once and reuse it whenever you need it. This can make your code more concise and easier to read.


#Tip 761.

Install the latest version of Unity.

Go to Edit > Preferences > External Tools.

Click the checkbox next to "Install MonoDevelop" and then click "OK".

Now, when you create a new C# script, it will open in MonoDevelop.


#Tip 762.

Be consistent with your naming conventions!

This will help make your code more readable and easier to understand for others.


#Tip 763.

if you are going to have three methods with names like
UpdateTwoDimensionalArrayWithUseOfNumber2D3D4D
, then perhaps you shouldn't retrieve the information from
userInput
or
stateOfArray
directly, instead make an
IUserInput
interface and an
IArrayState
interface.  This will make your code more extensible and easy for


#Tip 764.

If you want to create a new object from an existing object, you can use the Clone() method.


#Tip 765.

Here's a good programming pattern tip for Unity C#:

If you have a piece of code that needs to be executed on a regular basis, consider using a coroutine. Coroutines allow you to break up a piece of code into smaller parts that can be executed over a period of time. This can be helpful when you need to wait for a certain amount of time before executing the next line of code.


#Tip 766.

If you want to move an object towards another object in Unity, you can use the "Vector3.MoveTowards" function. This function takes in a starting position, an end position, and a speed, and will move the object towards the end position at the given speed.


#Tip 767.

To convert a string to a byte array, you can use the Encoding.ASCII.GetBytes method.


#Tip 768.

If you want to add a bit of spice to your game, try using particle effects! Particle effects can be used for a wide variety of things, such as making explosions, smoke, or even just making pretty graphics. To add a particle system to your scene, just go to the "GameObject" menu and select "Create Other > Particle System".


#Tip 769.

If you want to be able to use a function from another script, you need to make sure that the function is declared as public. For example, if you want to be able to call the function DoSomething from another script, you would need to declare it as follows:

public void DoSomething(){

//Function code goes here

}


#Tip 770.

When working with the System.Collections.Generic namespace, it is often useful to create a static class with extension methods for the collection types. This allows for a more concise and readable code, as well as improving the discoverability of the methods.

For example, consider the following code:

public static class CollectionExtensions { public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items) { foreach (var


#Tip 771.

If you want to create a floating effect for your game objects, you can use Unity's "rigidbody" component. By adding a rigidbody component to your game object, you can give it a "mass" property which will make it float in the air.


#Tip 772.

Let's say you have a List of type Vector3 that represents a cube. To ensure that each of your Vector3 objects only appear once in this list, use Linq's Distinct() function like this:

cube.Distinct();


If you need this to work for vectors with different lengths, you'll have to create your own implementation of EqualityComparer.


#Tip 773.

In Unity C#, you can use the Debug.Log() function to print messages to the console. This is useful for debugging purposes, or for simply printing out information that you want to see.


#Tip 774.

If you want to create a Destructible Mesh in Unity 3D, you can use the following function:

Mesh.CreateDestructibleMesh(Mesh originalMesh, Material material, float damageThreshold);


#Tip 775.

If you want to change the case of a string, you can use the ToLower() or ToUpper() method. For example:

string s = "Hello, world!";

s = s.ToUpper(); // s is now "HELLO, WORLD!"

s = s.ToLower(); // s is now "hello, world!"


#Tip 776.

you can use a
HashSet<T>
for building up a list of things. For example, if you create a
HashSet<string> mySet = new HashSet<string>();
and then add 5 items to it, e.g.
mySet.Add("item1");
and so on, then you can then get a list


#Tip 777.

Here's how you can use the keys of a dictionary as a list in C#:

var keys = myDictionary.Keys.ToList();


#Tip 778.

Try to avoid hardcoding the "Game" name. Instead, use an interface IGameManager or an abstract class.Also consider the following in your coding. These are all good things to have in mind when designing your package.


#Tip 779.

</b>

Use the using statement to ensure that disposable objects are properly disposed of. This is especially important when working with databases or other resources that need to be properly released when finished.

using (var disposableObject = new DisposableObject())
{
    // Use the disposable object here.
}


#Tip 780.

To get the current time, you can use the DateTime.Now property.


#Tip 781.

If a type tests true for the IsPrimitive type, it will also test true for the IsValueType type. Most value types test true for both IsPrimitive and IsValueType, including Bitcoin Network Difficulty Chart 01/06/ Gox hack online event chart by market.

In 2014, amidst major Bitcoin adoption, MtGox. Investors explain how bitcoin how betternet without vpn could make it to 0k part one Bitcoin rate history chart digital foundry: the ps


#Tip 782.

If you're going to read and convert Strings from a TextBox, and then write the contents of the Output Label.  you'll almost certainly want to wrap your call to Convert.ToInt32() in a try {} catch block.
Let's say, for instance, that the user enters the text "123" in the TextBox, and presses the "Write" button.  When your code calls Convert.ToInt32() on that string, it happily converts the string


#Tip 783.

Or if you want to massage the numbers, you can use Mathf.Repeat which resets a value [0 - duration) after it reaches or exceeds duration. This is useful for a moving object that needs to make a continuous motion around an object or along a path. It is the same as the % operator, but for floats:

float offset = ((float)milliSeconds - (float)startMilliseconds) / 1000.0f;
transform


#Tip 784.

Just make sure your classes are small.

Smaller classes are usually easier to maintain and test than large ones. They also tend to be more flexibile and reusable.


#Tip 785.

Model a piece of UI as a state machine.

This can be done by creating a State Machine class, which has a reference to the UI component that it controls. The State Machine class has a property for the current state of the UI, and methods for changing states.

The State Machine class also has event handlers for UI events, such as button clicks. These event handlers call methods on the current state object, which can perform the appropriate action for that event.

This approach


#Tip 786.

you can deserialize a json string (assuming it is valid json!) directly into a List of objects of any type you like using the
JsonConvert.DeserializeObject<T>
method like this:

List<MyObject> myObjectList = JsonConvert.DeserializeObject<List<MyObject>> (jsonString);


#Tip 787.

If you want to change the rotation of an object over time, you can use the following code:

transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime);


#Tip 788.

go not to your parent class/method, but instead of to your peers/ colleagues/ or interfaces, with this you maximize your composer and code reuse.



In general, it's a good idea to go to your peers, interfaces, or colleagues when you're looking for a particular piece of functionality. This maximizes your code reuse and makes your code more maintainable.


#Tip 789.

Programming Patterns

There is a great book called "Design Patterns" by the "Gang of Four" which outlines many common programming patterns. If you are not familiar with design patterns, I recommend reading up on them, as they can be extremely useful.

One common pattern is the "singleton" pattern. This is where you create a class that can only be instantiated once. This is often used for things like database connections, where you want to ensure that only one


#Tip 790.

https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/generics
The tip is on delegating responsibility for managing game objects to individual MonoBehaviours.

This is a good programming pattern because it makes it easier to manage different types of game objects. For example, if you have a MonoBehaviour that is responsible for managing enemies, it can easily keep track of all the enemies in the scene. This


#Tip 791.

you can create a prefab by selecting an object in your scene, then choosing
GameObject > Create Prefab
.


#Tip 792.

If you want to create a new object in Unity, you can use the Instantiate() method. This will create a new object at the specified location in the scene.


#Tip 793.

If you know when a value won't change during execution, declare it as readonly. Consider:

readonly int[] Marks = { 8, 6, 7, 9 };

Here the Marks array cannot be changed during the program's execution. Only when you have to initialize the array will you set it to the values you set it to here. Since you can change the values in the array without locking them as readonly, it means that you can also lock values in a method


#Tip 794.

In Unity, it's generally considered good practice to have your public methods be short and sweet, and your private methods be where the real heavy lifting happens. This is because Unity's MonoBehaviour EarlyUpdate, Update, LateUpdate, and FixedUpdate methods are called very frequently, so it's important to make sure they're not doing too much work.

One way to achieve this is to have your public methods simply call your private methods. For example, you might have a public


#Tip 795.

You can make a method that returns a value.

To do this, you first need to create a method that takes in a parameter. The parameter will be the value that you want to return. Then, you need to use the return keyword, followed by the value that you want to return.

Here's an example:

public int GetMyNumber() { return 5; }


#Tip 796.

When you start writing a new project in Unity containing blank C# scripts do this:

In your C# script files, type "ctrl + .". A menu will pop up. Choose the "Organize Usings" menu item. This will automatically add all the "using" statements your script needs at the top of the file. :)


#Tip 797.

As a best practice, it is recommended that you always use the var keyword when declaring a variable, unless the specific type is required for technical reasons. By using var, you can improve the readability of your code as well as make it less prone to errors.


#Tip 798.

If you have a lot of related data that you need to store together, consider using a class. Classes allow you to create your own custom data types, and you can use them to group together related data. This can make your code easier to read and understand.


#Tip 799.

Whenever you need to add more detail to an existing 3D model, you can use the Sculpting Tools to do so.

1. To access the Sculpting Tools, go to the Hierarchy window and select the GameObject you want to edit.

2. In the Inspector window, click on the Add Component button and select Sculpting Tools from the list.

3. The Sculpting Tools window will appear, and you can use the various tools


#Tip 800.

If you have an object that you want to move around in a circular motion, you can use the "RotateAround" function. This function will take an object and rotate it around a specified point.


#Tip 801.

If you want to convert a string to a byte array, you can use the System.Text.ASCIIEncoding.GetBytes method. For example:

string str = "Hello world!";

byte[] bytes = System.Text.ASCIIEncoding.GetBytes(str);


#Tip 802.

When working with collections, prefer the use of for each loops rather than for loops whenever possible. This is because for each loops automatically handle errors and cleanup, whereas for loops do not.


#Tip 803.

There's a lot you can do in terms of programming with Unity, but one simple tip is to make use of the "MonoBehaviour" class. This class provides a lot of functionality that can make scripting simpler and easier to understand.


#Tip 804.

How you constantly return error checked handles for Unity game engine components.

This is how you would check for an error when trying to get a handle to a Unity game engine component:

if (transform == null)

{

Debug.LogError("transform is null");

return;

}


#Tip 805.

always access data members only by their property getters/setters. Why? Because using properties drastically improves your code's maintainability and flexibility. Here's why and how.

Relying on properties allows your code to automatically adapt to changes within the data member's type

By training yourself to only access data members directly and by backing those data members with properties, your code automatically becomes more future-proof.

Suppose you have a data member in your code that represents the current


#Tip 806.

if you need t


#Tip 807.

You can create a method that takes a string and an integer as parameters. The method will print the string the specified number of times.

public void PrintString(string str, int num)
{
    for(int i = 0; i < num; i++)
    {
        Console.WriteLine(str);
    }
}


#Tip 808.

The method falls into the category of Family Type Pattern methods. Its purpose is to filter a source elements by matching a target element. For example: remove all employees who match an employee salary threshold, keeping only those who do not meet the salary threshold.

var result = employees.RemoveAll(employee => employee.Salary > threshold);


#Tip 809.

You can use the string.Format() method to insert values into a string.

Here's an example:

string myString = "I am a {0}";

string.Format(myString, "programmer");

This would output the string "I am a programmer".


#Tip 810.

When working with the String class in C#, it is often useful to use the StringBuilder class instead. StringBuilder is designed for situations where you need to modify a string frequently. It is more efficient than the String class because it does not create a new instance of the string every time it is modified.


#Tip 811.

If you want to create a more realistic environment, you can use Unity's built-in terrain engine. This will allow you to create mountains, valleys, and other terrain features.


#Tip 812.

Name some action that happens after waiting a few seconds. (for example, praying makes you feel better). An action that can take arbitrarily long is called a "coroutine".Here's how to wait a few seconds before changing a label to read "Complete"!This code is called when the player prays, and changes the label after a short delay. The full script looks like this:When Prayer is clicked, Prayer.cs invokes the AwaitPrayerComplete() coroutine. The


#Tip 813.

If you want to create a 3D text effect, you can use the Unity 3D Text Mesh component. This will allow you to create 3D text that can be seen from any angle. You can also use the Text Mesh Pro asset to create more advanced 3D text effects.


#Tip 814.

Create a script named 'Bomb.cs', then int the following.

public class Bomb : MonoBehaviour { public float explosionRadius = 5.0f; public float explosionForce = 1000.0f; public float explosionTimer = 3.0f; public GameObject explosionEffect; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void Explode () { // 1. Get all colliders within the explosion radius Collider


#Tip 815.

If you want to create a realistic water effect, try using a plugin like Houdini Ocean Toolkit. This will give you the ability to create waves and other effects that look realistic and are easy to control.


#Tip 816.

+
+If you want to create a prefab from a GameObject in your scene, you can use the UnityEngine.Object.Instantiate() method. This method will create a new instance of the prefab in your scene.
+
+To use this method, first create a GameObject in your scene. Then, add the following code to your script:
+
+// Create a new instance of the prefab
+GameObject prefabInstance = (Game


#Tip 817.

The
static
keyword in C# means you only have one instance at the assembly level of that particular item.  So a
static
class is really a singleton class.  You can use this to effectively create a 'global' or 'persisted' instance for multiple instantiations of your classes.
For example:

public static class MyGlobalClass
{
    private static Dictionary<string, string&


#Tip 818.

+
+If you need to format a string with curly braces, you can use the @ symbol:
+
+var s = @"This is a string with curly braces: { }";


#Tip 819.

If you want to create a game object at a specific position in the world, you can use the Instantiate() method. This method takes a prefab as an argument, and will create a new instance of that prefab in the world.


#Tip 820.

If you want to change the materials of your 3D model in Unity, you can do so by selecting your model in the Hierarchy, then going to the Inspector. In the Inspector, there is a Materials tab where you can select which materials you want to assign to your model.


#Tip 821.

If you want to create a truly immersive experience, try using Unity's Mecanim system to create realistic character animations. Mecanim makes it easy to create lifelike movements, and can even be used to lip sync character dialogue.


#Tip 822.

If you want to make aObject move towards another object, you need to useVector3.Lerp().


#Tip 823.

If you want to add a component to an object in Unity, you can use the AddComponent() method. For example, if you want to add a Rigidbody component to an object, you would use the following code:

object.AddComponent<Rigidbody>();


#Tip 824.

If you want to loop through a data structure and you have an indexer, you can use the `for each` loop.

Here's an example:


csharp
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

foreach (int number in numbers)
{
    Console.WriteLine(number);
}


#Tip 825.

If you use this code, it will disable the gravity for the rigidbody myRigidbody

// Disable Gravity:
myRigidbody.useGravity = false;


Maybe that will help you.


#Tip 826.

If you want to create a public static field in Unity 3D, you need to add the [PublicStatic] attribute to the field.


#Tip 827.

Use Count() to get a list of object counts.

For example, say you have a list of integers and you want to know how many of each integer there are. You can use Count() to do this:

var intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var intCounts = intList.GroupBy(i => i).Select(g => new


#Tip 828.

InstanceField.Clear uses the ImmutableCollection<T> class, which does not contain a Clear method.

To clear an ImmutableCollection<T>, you must use the .ToBuilder() method to create a mutable collection, and then clear that.


#Tip 829.

To create a basic countdown timer, you can use the built-in "Invoke" function. This function can be used to call a method after a specified amount of time has elapsed.

Here's an example of how you could use it to create a countdown timer:

using UnityEngine;

public class CountDownTimer : MonoBehaviour {

public float timeLeft = 10.0f;

public void Update()


#Tip 830.

If you want to make a game object move towards another object, you can use the "Transform.LookAt" method. This will make the object rotate so that it is facing the other object, and then move forward.


#Tip 831.

If you want to convert a string to a byte array, you can use the System.Text.Encoding.UTF8.GetBytes method.


#Tip 832.

If you're using LINQ to query data, it's a good idea to use the var keyword when declaring your query variable. This allows the compiler to infer the type of the query variable, which can make your code more concise and readable.


#Tip 833.

If you want to create a reusable component that can be used multiple times in your project, you can create a custom Unity C# script. To do this, first create a new C# script in your project. Then, open the script and add the following code:

public class MyCustomComponent : MonoBehaviour { // Add your code here }

This will create a new custom component that can be used like any other MonoBehaviour in Unity. You can add any


#Tip 834.

If you want to create a game object at a specific location, you can use the Instantiate() method. This method takes a prefab as an argument and will create a new instance of that prefab at the location specified.


#Tip 835.

How about using a three-state flag variable? You can use this variable to keep track of the current or last operation that was performed with the following three states:



-1: Undefined or no operation
0: Addition
1: Subtraction

Here's a simple example:

int flag = -1;
int result = 0;

Console.Write("Enter first number: ");
int num1 = Convert.ToInt32(


#Tip 836.

If you have a game object that you need to reference in multiple places, you can create a static instance of it. This will allow you to access the game object from anywhere in your code without having to keep track of a reference to it.

To do this, simply add the following line of code to your game object:

public static GameObject instance;

Then, in your code, you can reference the game object by using the following:

GameObject


#Tip 837.

If you find yourself writing a lot of code that looks like this:

someObject.SomeProperty = "some value";

someOtherObject.SomeOtherProperty = "some other value";

yetAnotherObject.YetAnotherProperty = "yet another value";

then you can probably simplify your code by creating a class that encapsulates all of those values:

class MyValues
{
    public string SomeProperty { get; set; }


#Tip 838.

If you are using
foreach
to iterate a
List
likelihood is you will want to
break
out of the loop at some point.   If possible don't use
break
.  Instead try to use
var index = myList.FindIndex(x => x.SomeConditionTestsTrue);  if (index > -1) myList


#Tip 839.

You can use the UnityEngine.Random class to generate random numbers.


#Tip 840.

There are two ways you can use
foreach
loops. If you want to be able to
modify the items in the collection, you can iterate over the collection by
reference:

foreach (var item in someCollection)
{
    // You can now modify item directly
}


If you don't want to be able to modify the items, you can iterate over the
collection


#Tip 841.

If you need to constantly check for certain conditions in your Unity game, it's generally best to use LateUpdate() instead of Update(). This is because Update() is called every frame, regardless of whether or not any conditions have changed. LateUpdate(), on the other hand, is only called after all Update() calls have been made, so you can be sure that any conditions you check for in LateUpdate() have actually changed since the last frame.


#Tip 842.

When you need to clear a variable from a subclass and you don't know how it was set, set it to null instead.

Depending on how the variable was set, clearing it with null may not work. In that case, you can try using the default keyword.


#Tip 843.

In procedural programming, the interface of an object is made up from
two parts or layers:

1) its _value layer_. This is the part of the object that contains its
   current state, like properties, fields and variables.

2) its _command layer_. This is the part of the object that allows you
   to _change_ (i.e. comand new states) value layer by submitting _commands_.
   The most common example


#Tip 844.


if (Input.GetMouseButtonDown(0)) { // left click down
    // Do something
}
if (Input.GetMouseButtonUp(0)) { // left click up
    // Do something
}


#Tip 845.

In Unity 3D, you can use the "Edit->Snap Settings" menu item to change the grid snap settings. This can be helpful when trying to line up objects in your scene.


#Tip 846.

If you need to quickly create a prototype or placeholder for an object in your scene, you can use Unity's built-in primitive objects. These include a cube, sphere, capsule, cylinder, plane, and quad. To create one of these objects, select GameObject > 3D Object from the menu bar. Then, choose the desired object from the list that appears.


#Tip 847.

If you want to add a little bit of variety to your game, you can use the Random.Range() function to generate random numbers. You can use these numbers to choose random objects or spawn points, or to create random variations of enemies.


#Tip 848.

Capitalize First Character .
Note: the x => x.First() part makes sure that this only capitalizes the first character for each string. Otherwise all characters would be uppercase.


#Tip 849.

How do you pick a random element from an array?

Here's one way to do it:

var array = new int[] {1, 2, 3, 4, 5};

var randomElement = array[Random.Range(0, array.Length)];


#Tip 850.

If you have a method that is doing something that could potentially throw an exception, you should put that method inside a try/catch block. This way, you can catch the exception and handle it appropriately.


#Tip 851.

If you want to create a water effect, you can use the particle system. To do this, create a plane and add a particle system to it. Then, in the particle system settings, choose the "Water" preset. This will give your plane a watery look.


#Tip 852.

when you need to change a member value of an object from differentcode places, refrain from rolling your own Handlers, Events and Delegates and use the property - that is the recommended way. Let's say, for example, that you have a Field game object inside a game and several Game Objects containing monsters in some other place.. The field contains a number header property that counts all the monsters that have reached the destination., without more precisions, it's not as much useful. The field could


#Tip 853.


List<string> searchTerms = new List<string>
{
    "tag1", "tag2", "tag3"
};

var listOfAllItems = new List<Item>
{
    item1, item2, item3, item4
};

var listOfItemsWithSearchTerms = listOfAllItems.Where(item =>


#Tip 854.

If you want to make your game more challenging, try adding in more enemies or obstacles.


#Tip 855.

you're in a collection of type,
IEnumerable<int>
.
You can convert the variable to an
ICollection<int>
using the following:

ICollection<int> yourCollection = yourEnumerableVariable.ToList();


#Tip 856.

If you're working on a large project with many different scenes, it can be helpful to create a master scene that contains all of the assets and game objects for your project. This master scene can then be used as a starting point for new scenes, or as a reference for existing scenes. This can help to keep your project organized and avoid duplication of assets and game objects.


#Tip 857.

If you want to create a reusable code block in Unity C#, you can define a method.


#Tip 858.

Create a prefab out of an object, then drag it into the scene. Doing this will save you having to create the object again if you need to use it in another scene, or even another project.


#Tip 859.

If you want to make a gameobject "disappear" when you click on it, you can use the OnMouseDown() function. For example:

void OnMouseDown() { Destroy(gameObject); }


#Tip 860.

If you need a conditional in your LINQ query, you can create a method that returns a Boolean and call that method with a lambda expression. For example:

public void Class1
{
    public static bool isEnabled(Task task)
    {
        return DateTime.Now.Subtract(task.start).TotalDays < 14;
    }

    public List<Task> getTasks()
    {


#Tip 861.

Try to avoid using exception handling as a way to control program flow.


#Tip 862.

When working with collections, prefer the LINQ extension methods over loops.

For example, this loop:

var list = new List<int> { 1, 2, 3, 4, 5 }; foreach (var item in list) { Console.WriteLine(item); }

Can be rewritten using LINQ's Where extension method like so:

var list = new List<int> { 1, 2, 3, 4, 5 }; list.


#Tip 863.

You can use the GetComponent method to get a reference to a component attached to a GameObject. For example, if you have a GameObject with a SpriteRenderer component attached, you can get a reference to the SpriteRenderer like this:

var spriteRenderer = gameObject.GetComponent<SpriteRenderer>();


#Tip 864.

If you have an object that you want to be able to drag around the scene, you can make it's collider a trigger, and then use OnTriggerStay2D to detect when the player is touching the object.


#Tip 865.

If you want to know if a certain key is being pressed, you can use the Input.GetKey() function. For example, if you want to know if the "a" key is being pressed, you can use the following code:



if (Input.GetKey("a"))

{

// do something

}


#Tip 866.

If you want to center a string within a given width, you can use the following code:



string s = "My String";

int w = 10;

Console.WriteLine(s.PadLeft((s.Length + w) / 2).PadRight(w));


#Tip 867.


|]  let n = Random(
|]  Seq.initInfinite(fun _ -> n.Next() % 10)
|]  |> Seq.maxNumBy Seq.head
|]  |> printfn "%A"
|]  
|]  >>> 13


From the type of Seq it's easy to


#Tip 868.

Encapsulate method calls in properties when the cash is expensive - like querying databases, altering WebGrids and The rest I have seen some googling about making them readonly, but with no success. you can leave the property if it's still it's incorrect value, or set it to the correct value if it's currently incorrect. SymptomsIn a C# class, use Generate Property Getter & Setterto create a public property that relies on another cached value.


#Tip 869.


var list = new[] {1, 5, 10, 20}
foreach (var point in (list.Count() - 1).To(0, i => i - 1))
{
    var from = list[point];
    var to = list[point - 1];
    Console.WriteLine("from: " + from + " to: " + to);
}


This prints:
<


#Tip 870.

To convert a string to title case, use the ToTitleCase method.


#Tip 871.

If you have a boolean method that is being used as a condition in an if statement, put an exclamation point (!) in front of the method call. For example, if you have a method named IsValid that returns true if a blog post is valid and false if it is not, you would put an exclamation point in front of the method call like this:

if (!IsValid(blogPost))
{
    // do something
}


#Tip 872.

If you have a GameObject that you need to move around in your scene and you want it to move smoothly, you can use the UnityEngine.Mathf.SmoothDamp() method. This will take care of all the interpolation for you and will make your object move smoothly.


#Tip 873.

If you have a LookAt method that needs to track an object that is moving, you can use the Quaternion.LookRotation method. This will let you create a rotation that tracks the object's movement.


#Tip 874.

If you want to move an object around the screen, you can use the "transform" property. For example, if you want to move an object to the right, you can use the following code:

transform.position += new Vector3(1,0,0);


#Tip 875.

When using a System.IO.Stream class, instead of wrap it in an IDisposable using statement just make a method like this.

public static void UsingFileStream(string path, Action<FileStream> action) { using (var fs = new FileStream(path, FileMode.Open)) { action(fs); } }

Then your code to read the entire file into a string becomes:

string s; UsingFileStream("path/to/


#Tip 876.

If you haven't already, you should get into the habit of coding event handlers, like
OnGUI()
, normally and not in their inline variants. For example, this code:

GUI.enabled = false;
if (GUI.Button("tmp"))
    print("clicked");


should be written like this:

private void OnGUI() {
    if (GUI.enabled = false)


#Tip 877.

You can create a custom event handler by using the event keyword.


#Tip 878.

Create a ScriptableObject asset for each unique data type that you need to store. This will allow you to easily serialize your data and store it in a convenient asset file.

To use this pattern, simply create a new ScriptableObject asset for each data type you need to store. Then, use the Unity Editor's "Serialize Object" menu option to serialize your data into the asset file.

This pattern is especially useful for storing level data, game configuration


#Tip 879.

Declare a static instance of your MonoBehaviour instead of referencing the MonoBehaviour directly. This will allow you to easily find and access your MonoBehaviour from anywhere in your code.

For example, instead of referencing the MonoBehaviour directly:

MonoBehaviour mb;

Declare a static instance of your MonoBehaviour:

static MonoBehaviour mb;


#Tip 880.

If you are using the LINQ to SQL classes, you can bind a ComboBox control to a LINQ query like this:

var query = from c in db.Categories
            orderby c.Name
            select c;

comboBox1.DataSource = query;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "CategoryID";


#Tip 881.

shorten your code by using the "ternary operator".

The ternary operator is a shorthand way of writing if/else statements.

For example, the statement

if (condition)
{
   //code to execute if condition is true
}
else
{
   //code to execute if condition is false
}

can be shortened to

condition ? //code to execute if condition is true


#Tip 882.

//
    //var stackOverflowSurveys = File
    //    .ReadAllLines(fileName)
    //    .Select(l => JsonConvert.DeserializeObject<SurveyResults>(l));
    //
    //In this example we are reading in a file that is a bunch of JSON strings and using Linq to turn them into SurveyResult objects.


#Tip 883.

If you want to convert a string to a number, you can use the built-in Convert class. For example, the following code will convert the string "5" to the number 5:

int num = Convert.ToInt32("5");


#Tip 884.

If you want to create a custom inspector for a script, you can create an editor script. Editor scripts are written in C# and allow you to customize the inspector for a script.


#Tip 885.

If you're ever working with a value type (like an int, decimal, DateTime, etc.) and you need to pass it into a method that requires a reference type (like an object), you can use the "box" keyword. For example, if you have an int variable named "myInt" and you need to pass it into a method that requires an object, you would do this:

object myObject = myInt;

This will "box"


#Tip 886.

If you want to quickly convert a string to a byte array, you can use the System.Text.Encoding.ASCII.GetBytes() method.


#Tip 887.

If you need to read data from
file byte by byte, you can use a BinaryReader.

Here's how you would use a BinaryReader to read a file byte by byte:

using (var reader = new BinaryReader( File.Open( "filename", FileMode.Open ) ) )
{
   while ( reader.BaseStream.Position != reader.BaseStream.Length )
   {
      byte data = reader.ReadByte();
      //


#Tip 888.

If you find yourself needing to write a lot of code to handle a particular data type, consider creating a custom type to represent that data. This will make your code easier to read and maintain, and will make it easier to work with the data in question.


#Tip 889.

If you want to get the position of an object in world space, you can use the Transform.position property.


#Tip 890.

(Note: I am currently running Unity 3D v4.6.0f3)

If you want to create a curved line in Unity 3D, you can use the LineRenderer component. First, add a LineRenderer component to your game object. Then, in the LineRenderer settings, set the "Material" property to "Standard". Next, in the "Start Color" property, set the color you want the line to start as.


#Tip 891.

If you want to perform an action on all items in a list, you can use the .ForEach() method. For example, if you have a list of strings and you want to print them all to the console, you can use the following code:

stringList.ForEach(s => Console.WriteLine(s));


#Tip 892.

Classes and interfaces contain functionality, but
they should be small and focused. A class or interface
that contains too much functionality is called a
"God Class" or "God Interface".

A "God Class" or "God Interface" is a class or interface that contains too much functionality. This can make the code difficult to maintain and understand. A good rule of thumb is to keep a class or interface small and focused.


#Tip 893.

myFunction()
{
    if (myVariable == true)
    {
        // do something
    }
}


#Tip 894.

If you need to force garbage collection, you can use GC.Collect().


#Tip 895.

If you want to create a random number between two values, you can use the UnityEngine.Random.Range() method. For example, if you want to create a random number between 1 and 10, you would use the following code:

int rand = UnityEngine.Random.Range(1, 11);


#Tip 896.

You can use the Input.GetAxis method to get input from the user. This can be used to get input from a joystick, gamepad, or keyboard.


#Tip 897.

If you have an IEnumerable<T> you can use Aggregate to get a single result after running an operation on each element.  For example, say you wanted to take a list of integers and sum them:

IEnumerable<int> integers = new[] { 1, 2, 3 };
int sum = integers.Aggregate((current, next) => current + next);


Aggregate gets


#Tip 898.

One tip for Unity 3D is to place objects on different layers and use the collision matrix to control which layers collide with each other. This can be useful for organizing your game objects and avoiding unnecessary collisions.


#Tip 899.

You can create extension methods for existing types! This can be really useful for adding functionality to types that you don't have control over, such as the built-in types in the .NET Framework.

To create an extension method, you need to create a static class with a static method that takes the type you want to extend as its first parameter. The parameter needs to be marked with the this keyword:

public static class MyExtensions
{
    public static void


#Tip 900.

If you want to execute a piece of code only when a specific condition is met, you can use an if statement.

if (condition)
{
   // Code to execute
}


#Tip 901.

The using statement is a C# directive that tells the compiler that you intend to use a class that is defined in an outside assembly. The using statement obviates the need for fully qualifying namespaces when you are using types in an assembly.

Here's how to use the using statement:

using System;

class Test

{

public static void Main()

{

Console.WriteLine("Hello, world!");

}


#Tip 902.

If you want to speed up the process of creating 3D models, consider using a 3D modeling program. There are many different programs available, but some of the most popular ones include Maya, 3ds Max, and Cinema 4D. These programs will allow you to create high-quality 3D models quickly and easily.


#Tip 903.

If you want to create a custom inspector for a script, you can use the CustomEditor attribute. For example,

[CustomEditor(typeof(MyScript))]

public class MyScriptEditor : Editor

{

public override void OnInspectorGUI()

{

// ...

}

}


#Tip 904.

If your program is thrown off by having its main parameter types declared as
string
,
int
, and
bool?
, you can always use an overload:

static void Main(string args)
{
  Main(args.Split());
}
static void Main(string[] args)
{
  Main(args.Select(int.Parse).ToArray());
}
static void


#Tip 905.

If you add a listener to your script for
OnMouseDown()
, it will fire when the player clicks on your object. If you add a listener for
OnMouseUp()
, it will fire when the player releasing clicks on your object.

public class ClickScaler : MonoBehaviour {
    public float factor = 1.5f;

    private Vector3 _startScale;

    private void Awake()


#Tip 906.

Use an editor script to automatically attach a script to your main camera.

This can be done by creating a new C# script in your Unity project, and then adding the following code:

using UnityEngine;

public class CameraScript : MonoBehaviour {

    void Awake () {
        // Attach this script to the main camera automatically
        Camera.main.gameObject.AddComponent<CameraScript>();
    }


#Tip 907.

If you need to debug something in your code, you can use the "Debug.Log" function. This will print out a message to the Unity console, which can be helpful for tracking down errors or understanding what your code is doing.


#Tip 908.

One tip for using Unity 3D is to take advantage of its asset store. This is a great place to find models, textures, and other assets that can be used in your project. Additionally, theUnity community is very active and there are many resources available online to help you get started.


#Tip 909.

In the project window, expand the Scripts folder to reveal the files inside,
and expand the one called LevelManager. All the way at the bottom, you should see two public methods called
LoadNextLevel() and LoadLevel().
The first one is called when you reach the end of the current level.
The second one is called when you click the Retry button on the Game Over screen.


#Tip 910.

If you're working with strings, it's often helpful to use the StringBuilder class instead of concatenating strings together with the + operator. StringBuilder is designed for efficiently building up strings, and can be much faster than concatenating strings together manually.


#Tip 911.

To add an item to a list, you can use the Add method.


#Tip 912.

When working with strings, it is often useful to use the StringBuilder class instead of the String class. This is because the String class is immutable, meaning that every time you modify a string, a new instance is created. This can be expensive in terms of both memory and processing power. The StringBuilder class, on the other hand, is mutable, meaning that it can be modified without creating a new instance. This can be much more efficient, especially when working with large strings.


#Tip 913.

If you have a MonoBehaviour that you only ever want to have one instance of in your scene (like a GameManager), you can make it a static class.

To do this, just add the keyword "static" to your MonoBehaviour class declaration, like so:

public static class GameManager : MonoBehaviour {

...

}


#Tip 914.

If you have a string and that string should always end with the same character, a good practice is to "pad" the string with that character until it reaches the desired length.  You can do this with the
PadRight
method like this:

string myString = "This should always end with an!";
int desiredLength = 50;
myString = myString.PadRight(desiredLength, '!');
</code


#Tip 915.

When you have a MonoBehaviour-derived class that needs to do some work in the Update loop, but you only want that work to happen once per frame, you can use the following pattern:

private bool _shouldDoWorkThisFrame = true; void Update() { if (_shouldDoWorkThisFrame) { // do work here _shouldDoWorkThisFrame = false; } } void LateUpdate() { _shouldDoWorkThisFrame = true; }


#Tip 916.

If you want to create a prefab from a game object, you can use the following code:

var prefab = PrefabUtility.CreatePrefab("Assets/Prefabs/MyPrefab.prefab", gameObject);


#Tip 917.

When working with the System.Collections.Generic namespace, it is often useful to create a static class with generic extension methods. This allows you to add functionality to the built-in collection types without having to create a new derived type.

For example, suppose you want to create a method that returns a random element from a list. You could write a static method like this:

public static class MyExtensions { public static T GetRandomElement<T>(this I


#Tip 918.

Model - Generate Json - Handle Json - Save Json - Load Json.

This programming pattern can be used for a number of different tasks, such as working with databases, file input/output, or web programming. It is a good way to keep your code modular and maintainable.


#Tip 919.

If you want to create an empty string, you can use the string constructor:

string myString = new string("");


#Tip 920.

To get the proper type name of an object at runtime, use the following:

object myObject = ...;
string typeName = myObject.GetType().Name;


#Tip 921.

You can use the "Time.time" function to get the current time in seconds. This is useful if you want to do something after a certain amount of time has passed. For example, you could use it to make a countdown timer.


#Tip 922.

If you want to ensure that a particular block of code is only executed once, you can use the lock keyword. For example:

lock (someObject)
{
    // Only one thread can enter this code at a time
}


#Tip 923.

If you want to create a water pool that your character can swim in, you can use a simple cube for the pool's bounds. Then, add a Plane object to the scene and position it so that it intersects the cube at the water's surface. Finally, add a Physics Material to the Plane and set its bounciness to 1. This will cause the Plane to act as a trampoline, launching the character into the air when they walk on it.


#Tip 924.

Say you have a list of objects, and you want to iterate through them, but you also want to keep track of the index. You can do this by using the System.Collections.Generic.List class:

List<GameObject> myList = new List<GameObject>();

foreach (GameObject obj in myList)

{

int index = myList.IndexOf(obj);

// do something with obj and


#Tip 925.

To create a wireframe mesh, you need to go into the Physics settings and change the "Draw Wireframe" option to true.


#Tip 926.

You can use the Debug.Log() function to print messages to the Unity console. This is useful for debugging purposes, as it allows you to see what is happening in your code as it is running.


#Tip 927.

To create a basic car AI system in Unity, you will need to create a few scripts. The first script, "CarController.cs", will be attached to the car object and will be used to control the car's movement. The second script, "CarAI.cs", will be attached to an empty game object and will be used to manage the AI behaviour. You can find more information on how to create this system here: https://www.raywenderlich.


#Tip 928.

You can create a "day-night" cycle by using a directional light with a light cookie, and setting the light cookie's angle property to 0 degrees during the day, and 180 degrees at night.


#Tip 929.

You can create a method that will run when the program starts. This is called a "Main" method. The Main method must be static, and it must have a string array parameter.


public static void Main(string[] args)
{
   // Put your code here
}


#Tip 930.

If you want to make a game object face the direction it is moving, you can use the Transform.LookRotation() method. This will take a Vector3 direction and will rotate the transform to face that direction.


#Tip 931.

if you need to check a multiple possible conditions, a "switch" statement is usually the best option. But if those conditions are entirely about a single value, an "if" statement is usually better. For example, "if (value == 1 || value == 3 || value == 5)" is usually more clear than a "switch".


#Tip 932.

If you have a script that you'd like to attach to a number of different game objects, you can use the
[RequireComponent]
attribute. The C# code would look like this:

[RequireComponent(typeof( Rigidbody ))]
public class Example : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is


#Tip 933.

You can navigate to any directory on your machine by specifying an absolute path:
Path.Combine("C:\\", "Tools"); Hope this helps!


#Tip 934.

from the Main(string[] args) method in your Program class, call System.Console.Write() or System.Console.WriteLine() and pass in the string "Hello, world!" (without the quotes).


#Tip 935.

Point Click Move Player

To make a player move to wherever you click on the screen, you can use Unity's built in Input.GetMouseButtonDown() method. Check out the code example below:

void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector2 mousePos2D = new Vector2(mousePosition.x, mousePosition.y);


#Tip 936.

When creating a menu system, you can use the OnGUI() method to handle all of your menu drawing. So, for example, you could have a MainMenu class that inherits from MonoBehaviour, and that class would override OnGUI(). In the OnGUI() method, you could use GUI.Button() to draw your menu buttons, and handle the button clicking events with an if statement.


#Tip 937.

If you're ever writing code that uses the System.Text.RegularExpressions library, be sure to include the "using System.Text.RegularExpressions" namespace at the top of your file. This will save you a lot of typing and make your code more readable.


#Tip 938.

If you want to iterate through a list of items, you can use the foreach loop. This loop will execute a block of code for each item in the list.


#Tip 939.

If you want to create a new object in Unity, you can use the Instantiate() method.


#Tip 940.

If you want to create a realistic water effect, you can add a water prefab to your scene and then configure the settings in the Unity editor. To do this, first select the water prefab in the Project window, then in the Inspector window, select the Edit button. This will open the water prefab in the Prefab Editor. Next, in the Prefab Editor, select the Settings tab. Here you can adjust the wave height, wind speed, and other parameters to create


#Tip 941.

If you want to create a game that looks like it's set in the past, you can use Unity's Time Of Day tool to adjust the lighting in your scene.


#Tip 942.

When working with collections, it is often useful to use the foreach loop. This loop will iterate over each element in the collection and perform the specified operation.


#Tip 943.

If you want to create a 3D game, but don't have any experience with 3D graphics or game development, you can try using the Unity 3D game engine. It's a free, easy-to-use tool that can help you create professional-looking 3D games.


#Tip 944.

Add a C# script to your project. Then, in that script, you can use the following code to make a GameObject spawn at a random position on the screen:

public class SpawnRandomly : MonoBehaviour { public GameObject prefab; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.Space)) { Instantiate(prefab, new Vector3(Random.


#Tip 945.

To create a custom event, you need to first create a delegate. Delegates are like function pointers, and they allow you to reference a method without having to explicitly invoke it. Next, you create an event handler, which is a method that will be called whenever the event is fired. Finally, you need to add an EventHandler to the event, which will register the event handler with the event.

Here's an example:

public delegate void MyEventHandler(object


#Tip 946.

Create a "Particle" classructure and create/initialize a particle as:



Particle p = new Particle(Vector3.zero, Vector3.zero, 1.0f);



The first Vector3 parameter is the position of the particle, the second Vector3 parameter is the velocity of the particle, and the float parameter is the particle's mass.


#Tip 947.

When you want to Instantiate an object at a position, you can use this code:

Instantiate (object, position, rotation);

where object is the object you want to instantiate, position is the position you want to instantiate it at, and rotation is the rotation you want it to have.


#Tip 948.

If you want to create a 3D object that can be interacted with, you can use the built-in 3D object creator. To do this, go to the GameObject menu, then select 3D Object > Cube. This will create a 3D cube in the scene view.


#Tip 949.

If you want to create a custom Component in Unity 3D, you can create a script that inherits from MonoBehaviour. Then, you can add your custom Component script to a GameObject just like any other Component.


#Tip 950.

If you want to create a new object and assign it to a variable, you can use the "new" keyword followed by the object's type. For example:

MyObject myObj = new MyObject();


#Tip 951.

If you want to change the value of a variable over time, you can use the += operator. For example, if you have a variable named "count" that starts at 0, you can increment it by 1 every frame using the following code:



void Update()

{

count += 1;

}


#Tip 952.

In C#, you can use LINQ to query data from various data sources. For example, you can use LINQ to query data from a database or from an XML file.


#Tip 953.

If you want to create a new GameObject in Unity 3D, you can use the "GameObject.CreatePrimitive" method. This will create a new GameObject with a Primitive mesh type (Cube, Sphere, Capsule, Cylinder, Plane, or Quad).


#Tip 954.

<br>

If you want to add a reference to a DLL, you can use the "Add Reference" dialog box in Visual Studio.


#Tip 955.

Use 'ref' to pass in more than one Value Type. It's more efficient because it doesn't have to create copies of the variables like passing in more than one Value Type normally.

class MyClass
{
        void MyFunction(ref int a, ref int b)
        {
                a = 0;
                b = 0;
        }
}


#Tip 956.

This tip is useful for when you want to run some code when an object is destroyed. For example, you may want to play a sound effect when an enemy is destroyed.

To do this, you can use the OnDestroy method. This method is called when an object is destroyed, so you can put your code in here.


#Tip 957.

To add two numbers, you can use the '+' operator:

int a = 1;
int b = 2;
int c = a + b;

Console.WriteLine(c); //Outputs 3


#Tip 958.

when you have a directional light in your scene, you can create a subtle 'fade to black' effect at the edges of the screen by setting the light's shadowStrength property to a value between 0 and 1.


#Tip 959.

If you want to make a method that can be called without an object instance, you can use the static keyword.


#Tip 960.

If you want to create a 3D game, one of the first things you need to do is create a 3D environment. This can be done in Unity by creating a 3D object and then setting its position and scale.


#Tip 961.

try using Scriptable Objects to seperate your datas.
This enables you to store data, like stats, and since they are assets themselves, they are stand alone in your project.
Great and clean way to do stats and not overcomplicating public variables or serialize data to a text field and read/write them ingame.
Patrick


#Tip 962.

In Unity 3D, you can create prefabs of your game objects. This allows you to reuse the same game object in your scene without having to create it from scratch each time.


#Tip 963.

In your Unity project, create a folder called "Scripts" and put all your C# code in there. This will keep your project organized and make it easier to find your scripts.


#Tip 964.

The easiest way to create a Console application in Visual Studio is to use the File->New->Project menu. In the resulting dialog, scroll down the list of project types and select the "Console App (.NET Core)" project type.


#Tip 965.

If you want to make a gameobject's position always relative to another gameobject's position, you can use transform.parent.

For example, if you want an object to be positioned relative to the player, you can set its parent to the player. Then, when the player moves, the object will automatically move along with it.


#Tip 966.

If you want to check if a GameObject is within a certain area, you can use Physics.CheckSphere.

To use this, you need to first create a Vector3 that represents the center of the area you want to check, and then a float that represents the radius of the area.

Once you have those, you can use Physics.CheckSphere like this:

if (Physics.CheckSphere(center, radius))

{

//


#Tip 967.

If you're working with the IDisposable interface, make sure to implement the Dispose method in your class. This will ensure that your class can be properly disposed of when it is no longer needed.


#Tip 968.

If you are working on a project in Unity that requires a lot of different textures, it can be helpful to create a texture atlas. A texture atlas is a single texture that contains all of the other textures in your project. This can be helpful because it can reduce draw calls, which can improve performance.


#Tip 969.

Use the Singleton Pattern.
The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.
This is useful in Unity because you often want to access the same Manager class from multiple Scripts.

Here's how to implement the Singleton Pattern in Unity:

First, create a Manager class. This class can be anything you want, but for the sake of example, let's say it's a Game Manager class.


#Tip 970.

If you want to create a particle effect, go to the Assets store and download the Shuriken Particle System.


#Tip 971.

If you want to find all game objects with a certain tag, you can use the following code:

GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag("TAG_HERE");


#Tip 972.

Check for null before accessing any member of an object.

For example, if you have a script that accesses the transform of an object, you should check for null first:

Transform t = obj.transform;
if (t != null)
{
    // access members of t
}


#Tip 973.

If you want to add a little something extra to your game, try using the "LayerMask" property in the "Physics" section of the "Unity 3D" menu.LayerMask allows you to specify which layers will be affected by collisions.


#Tip 974.

If you want to create a new object, you can use the "Instantiate" function.

Instantiate(myObject, transform.position, transform.rotation);


#Tip 975.

every time your mouse enters a GameObject it will keep executing the OnMouseEnter function as long as the mouse remains inside that object. This happens even if the object is disabled in the Hierarchy!

To prevent this behaviour, you can check whether the object is active in the Hierarchy before executing the rest of the OnMouseEnter code:

void OnMouseEnter()
{
    if(gameObject.activeSelf)
    {
        // Your code here


#Tip 976.

If you want to create a new object at the origin of the scene, you can use the Instantiate() method. This method takes a GameObject as a parameter and creates a new instance of it in the scene.


#Tip 977.

If you need to generate a random number within a certain range, you can use the System.Random class. For example, if you wanted to generate a random number between 1 and 10, you could use the following code:

System.Random random = new System.Random();

int r = random.Next(1, 11);


#Tip 978.

Lazy initialization means that the object or value will not be created until it is first used.

This can be useful if you have an object that is expensive to create, but you don't always need it. Lazy initialization can help improve performance by deferring the creation of the object until it is actually needed.

To lazy initialize an object, you can use the Lazy<T> class. For example, the following code lazily initializes a string:


#Tip 979.

If you want to create a believable and immersive environment, try to use as many real-world sounds as possible. For example, instead of using a generic "explosion" sound effect, try recording the sound of a real explosion. This will help to create a more believable and immersive environment for your game.


#Tip 980.

If you need to invoke a delegate, and that delegate may be null, use the "?" operator:

myDelegate?.Invoke(myArg);

This will check to see if the delegate is null before invoking it.


#Tip 981.

If you want to create a new string based on an existing string, you can use the String.Format method. For example, if you have a string that contains a name and you want to create a new string that contains the name in uppercase, you could use the following code:

string name = "John Smith";

string uppercaseName = String.Format("{0}", name.ToUpper());


#Tip 982.

If you want to make a GameObject's Collider automatically adjust to its Mesh, you can use the "Auto Generate" checkbox in the Collider component.


#Tip 983.

If you need to check if a string is null or empty, you can use the following code:

string s = "";

if (string.IsNullOrEmpty(s))
{
    // string is null or empty
}


#Tip 984.

If you want to create a realistic fog effect in your scene, you can use the built-in fog settings in the Unity engine. To do this, go to your scene's Lighting settings (found in the Window menu) and enable Fog. Then, you can adjust the density, color, and start and end distance of the fog to get the desired effect.


#Tip 985.

How To: Create a .pny file from an .snk file in C#.


#Tip 986.

On MonoDevelop 5, for example, you can add this to the start of your script:

#region Debug
static void debug(params object[] args)
{
    System.Linq.Enumerable.ToList(args).ForEach(o => Console.Write(o + " "));
    Console.WriteLine("");
}
#endregion


and then you can use:


#Tip 987.

If you want to move an object around constantly, you can use the Transform.Rotate method.


#Tip 988.

Putting code under #if ENVIRONMENT conditions

This allows you to put code that is only relevant to a certain environment (e.g. Development, QA, or Production) and have that code automatically excluded when compiling for a different environment.

For example, you might want to put some debug logging code under a #if DEVELOPMENT condition so that it is only included when compiling for the Development environment.

To do this, you can use the following


#Tip 989.

Program in components.

Components are one of the fundamental principles of Unity and game development in general. By thinking in terms of components, you can more easily modularize your code and make it more reusable.

For example, say you're making a simple 2D game. You might have a player component, an enemy component, and a projectile component. Each of these would have their own script with logic specific to that component.

This makes it easier to develop


#Tip 990.

If you have a public method that you only want to be called from within the same class, you can prefix it with an underscore. For example:



public void _DoSomething()

{

// ...

}


#Tip 991.

Download and import the Unitypackage for Umbra 3 from http://www. Umbra 3 is a occlusion culling system that can significantly improve the performance of your game.


#Tip 992.

In C#, you can use the "as" keyword to perform a type cast that will return null if the cast is not possible:

int? x = "5" as int?;

Console.WriteLine(x); // prints "5"


#Tip 993.

Try using the

@Html.Partial()
helper method to render any child views you need. If you
provide the name of the child view without providing a view model, the child view will render using the view model of the parent, but with a couple small exceptions.
The first is that if a child view has these using statements:

using System.Web.Mvc;
using System.Web.Mvc


#Tip 994.

You can use C# to create LINQ to SQL classes that allow you to easily query a database.


#Tip 995.

If you want to create a new object in Unity 3D, you can use the "GameObject->Create New" menu option. This will bring up a dialog where you can enter the new object's name, choose its type, and set its position and rotation.


#Tip 996.

If you want to create a new Unity project with a specific name and location, you can use the "Create New Project" button in the Unity Editor. This will open a new project window, where you can specify the name and location of your project.


#Tip 997.

consider using properties for public fields, as properties have mandatory memory fences built-in for most accessor operations.


#Tip 998.

"Use a property to hold an inspector reference to another physicist object, with a check to ensure it's not null"
– Unity Community

For example, if you have a script that needs to reference another object in the scene, you can use a property to hold a reference to that object:

public class MyScript : MonoBehaviour {
    [SerializeField]
    private PhysicsObject otherObject;

    void Update() {
        if (otherObject


#Tip 999.

If you want to create a function that will be called every frame, you can use the Update function. Update is called automatically by Unity every frame.



Here's an example:

void Update()

{

Debug.Log("This will be printed every frame");

}


#Tip 1000.

If you find yourself frequently needing to do the same thing to a bunch of different objects, consider writing a helper method to encapsulate that functionality. For example, suppose you often need to set the position of an object to a random point within some radius. You could write a helper method like this:

public static void SetPositionToRandomPointInRadius(this Transform transform, float radius) { Vector3 randomPoint = Random.insideUnitSphere * radius; transform.position