SlideShare ist ein Scribd-Unternehmen logo
1 von 78
C# FOR UNITY -
ADVANCE TECHNIQUE
PRESENTER: DUONG HOANG THANH
CONTENTS
• Multithreading
• Iterator
• Co-routine
• Delegate
• Event
• Lambda
• Other Techniques
• LINQ
MULTITHREADING
C# THREAD
void MethodA()
{
for (int i = 0; i < 100; i++)
Console.Write("0");
}
…
Thread t = new Thread(MethodA);
t.Start();
YOU CANNOT SPAWN THREADS IN UNITY ?
• It’s a myth. Many people are confusing Unity coroutines with threads.
• Let’s get this straight: Coroutines have nothing to do with threads.
• Coroutine is only a way to delay code execution without too much effort.
• It’s really a great method of writing game code when some routines are needed to be
executed in sequence over a time (like animations),
• but everything is still done in a single thread.
THREADS IN UNITY
WHEN THREADS ARE BAD
• Threads are dangerous, so you must be very careful when synchronizing
things back.
• You also need to remember that Unity API is not thread safe, so all calls to
Unity API should be done from the main thread.
WHEN THREADS ARE GOOD
• When you’re computing some expensive and/or long-term operations. Like:
• AI
• Pathfinding
• Network communication
• Files operations
ITERATOR
WHAT IS ITERATOR
• An iterator is a method, get accessor, or operator that performs a custom
iteration over an array or collection class by using the yield keyword.
• The yield return statement causes an element in the source sequence to be
returned immediately to the caller before the next element in the source
sequence is accessed.
• Although you write an iterator as a method, the compiler translates it into a
nested class that is, in effect, a state machine. This class keeps track of the
position of the iterator as long the foreach loop on the client code continues.
ITERATORS OVERVIEW
• Is a section of code that returns an ordered sequence of values of the same type.
• Can be used as the body of a method, an operator, or a get accessor.
• yield return statement to return each element in turn.
• yield break ends the iteration.
• Multiple iterators can be implemented on a class.
foreach(int x in SampleClass.Iterator2){}
• Return type must be IEnumerable, IEnumerator, IEnumerable<T>, or IEnumerator<T>.
• Are the basis for the deferred execution behavior in LINQ queries.
ITERATOR EXAMPLE
public class DaysOfTheWeek : System.Collections.IEnumerable {
string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
public System.Collections.IEnumerator GetEnumerator() {
for (int i = 0; i < days.Length; i++) {
yield return days[i]; }
}
}
…
DaysOfTheWeek week = new DaysOfTheWeek();
// Iterate with foreach
foreach (string day in week) {
System.Console.Write(day + " "); }
HOW DOES FOREACH WORK?
public void do_stuff() {
IEnumerator foo = bar.GetEnumerator();
foo.MoveNext();
print(foo.Current);//print 1 to console
foo.MoveNext();
print(foo.Current);//print 5 to console
}
public IEnumerable<int> bar(){
yield return 1;
yield return 5;
}
COROUTINE IS AN ITERATOR
public IEnumerator InternalRoutine(IEnumerator coroutine){
while(true){
if(!coroutine.MoveNext()){
yield break;
}
object yielded = coroutine.Current;
Debug.Log(yielded);
yield return coroutine.Current;
}
}
COROUTINE
COROUTINE
• A special type of function used in Unity
• to stop the execution until sometime or certain condition is met,
• and continues from where it had left off.
• It is essentially a function declared with a return type of IEnumerator
• and with the yield return statement included somewhere in the body.
• The yield return line is the point at which execution will pause and be resumed the
following frame
START & STOP COROUTINE
• The start of a coroutine corresponds to the creation of an object of type coroutine.
public Coroutine StartCoroutine(string methodName, object value = null);
public void StopCoroutine(string methodName);
public Coroutine StartCoroutine(IEnumerator routine);
public void StopCoroutine(IEnumerator routine);
public void StopAllCoroutines();
IEnumerator MyCoroutine(){yield return null;}
IEnumerator MyCoroutineOneParam(int i){yield return null;}
IEnumerator MyCoroutineManyParams(int i, int j){yield return null;}
COROUTINE UPDATE
Coroutine is tied to the MonoBehaviour component that
hosted the call.
EXAMPLEvoid Start() {
print("Start method");
StartCoroutine(TestCoroutine());
print("Start method ends");
}
IEnumerator TestCoroutine() {
print("TestCoroutine");
while(true) {
print("Here");
yield return null;
print("There");
} }
void Update(){print("Update");}
• It logs as:
Start method
TestCoroutine
Here
Start method ends
Update
There
Here
Update
There
Here
DESTROY GAME OBJECT WILL STOP COROUTINE
void OnCollisionEnter(Collision col)
{
if(col.gameObject.CompareTag("Rocket"))
{
StartCoroutine(Explosion());
Destroy(this.gameObject);
}
}
WHAT YOU CAN YIELD
• null – the coroutine executes the next time that it is eligible
• WaitForEndOfFrame – the coroutine executes on the frame, after all of the rendering
and GUI is complete
• WaitForFixedUpdate – causes this coroutine to execute at the next physics step, after all
physics is calculated
• WaitForSeconds – causes the coroutine not to execute for a given game time period
• WWW – waits for a web request to complete (resumes as if WaitForSeconds or null)
• Another coroutine – in which case the new coroutine will run to completion before the
yielder is resumed
• yield break – immediately stops the coroutine.
• …
CONVERT TO COROUTINE
• Auto called methods of MonoBehaviour that return IEnumerator will be
treated as Coroutine
• But can we stop them by StopCoroutine ?
private IEnumerator Start()
{
Debug.Log("Start method");
yield return StartCoroutine(TestCoroutine());
Debug.Log("Start method ends");
}
WHAT’S WRONG?
private IEnumerator Start()
{
Debug.Log("Start method");
yield return
StartCoroutine(TestCoroutine());
Debug.Log("Start method ends");
}
private IEnumerator Start()
{
Debug.Log("Start method");
yield return (TestCoroutine());
Debug.Log("Start method ends");
}
DOWNLOAD ITEM
private IEnumerator DownloadItem(string url, Action callback) {
if(string.IsNullOrEmpty(url))
yield break; // wrong url, stop the coroutine
WWW www = new WWW(url); // Start the downloading
yield return www; // Wait for the end of the downloading
if(www.error != null){ // Something went wrong
// Handle error
yield break;
}
// Take care of the www object
if(callback != null) {
callback ();
} }
WAITING FOR THE END OF A DOWNLOADING
private IEnumerator Start()
{
DisplayUIMessage("Loading...");
yield return StartCoroutine(DownloadItem(url, StartLevel));
}
private void StartLevel(){
// Set UI Off
// start level
}
COROUTINE SUMMARY
• Coroutines are a really good way of making a sequence of operations happen over
time or when some external process is completed
• Coroutines are not threads and are not asynchronous
• Nothing else is running when your coroutine is executing
• Your coroutine will resume when the conditions of your yield statement are met
• Coroutines are inactive when the script is disabled or the object is destroyed
• yield return new WaitForSeconds is dependent on game time which is affected by
Time.timeScale
DELEGATE
DELEGATE
• A type that represents references to methods with a particular parameter list
and return type.
public delegate int PerformCalculation(int x, int y);
• When you instantiate a delegate, you can associate its instance with any
method with a compatible signature and return type.
• You can call the method through the delegate instance.
USING DELEGATE
public class DelegateScript : MonoBehaviour {
delegate void MyDelegate(int num);
MyDelegate myDelegate;
void Start () {
myDelegate = PrintNum;
myDelegate(50);
}
void PrintNum(int num) {
print ("Print Num: " + num);
}
DELEGATE OVERVIEW
• Are like C++ function pointers but are type safe.
• Allow methods to be passed as parameters.
• Can be used to define callback methods.
• Can be chained together; for example, multiple methods can be called on a
single event.
• Methods do not have to match the delegate type exactly.
DELEGATE AS CALLBACK
public class DelegateScript : MonoBehaviour {
delegate void UpdateHandler();
public UpdateHandler onUpdate;
void Update () {
if (onUpdate != null) {
onUpdate();
}
}
ACTION DELEGATE
namespace System
{
public delegate void Action();
public delegate void Action<T>(T obj);
public delegate void Action<T1, T2>(T1 arg1, T2 arg2);
public delegate void Action<T1, T2, T3>(
T1 arg1, T2 arg2 , T2 arg3);
public delegate void Action<T1, T2, T3, T4>(
T1 arg1, T2 arg2 , T2 arg3 , T2 arg4);
}
FUNC DELEGATE
namespace System
{
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg1);
public delegate TResult Func<T1, T2, TResult>(T arg1, T arg2);
public delegate TResult Func<T1, T2, T3, TResult>(
T arg1, T arg2, T arg3);
public delegate TResult Func<T1, T2, T3, T4, TResult>(
T arg1, T arg2, T arg3, T arg4);
}
USING VARIANCE IN DELEGATES
• When you assign a method to a delegate, covariance and contravariance
provide flexibility for matching a delegate type with a method signature.
• Covariance permits a method to have return type that is more derived than
that defined in the delegate.
• Contravariance permits a method that has parameter types that are less
derived than those in the delegate type.
COVARIANCE
class Mammals{}
class Dogs : Mammals{}
class Program {
public delegate Mammals HandlerMethod();
public static Mammals MammalsHandler() { return null; }
public static Dogs DogsHandler() { return null; }
static void Test() {
HandlerMethod handlerMammals = MammalsHandler;
// Covariance enables this assignment.
HandlerMethod handlerDogs = DogsHandler;
}
}
CONTRAVARIANCE
public delegate void Action<in T>(T obj)
public class Person { }
public class Employee : Person { }
class Program {
static void AddToContacts(Person person) { }
static void Test() {
Action<Person> addPersonToContacts = AddToContacts;
// Contravariance enables those assignments.
Action<Employee> addEmployeeToContacts = AddToContacts;
addEmployeeToContacts = addPersonToContacts;
}
}
EVENTS
EVENTS
• Events enable a class or object to notify other classes or objects when
something of interest occurs.
• The class that sends (or raises) the event is called the publisher and the
classes that receive (or handle) the event are called subscribers.
• Events in the .NET Framework are based on the delegate model. The delegate
model follows the observer design pattern, which enables a subscriber to
register with, and receive notifications from, a provider.
DECLARE & USE EVENT
delegate void MsgHandler(string s);
class Class1 {
public static event MsgHandler msgNotifier;
static void Main(string[] args) {
Class1.msgNotifier += new MsgHandler(PipeNull);
Class1.msgNotifier("test");
}
static void PipeNull(string s) { return; }
}
EVENTS OVERVIEW
• The publisher determines when an event is raised; the subscribers determine what action is taken
in response to the event.
• An event can have multiple subscribers. A subscriber can handle multiple events from multiple
publishers.
• Events that have no subscribers are never raised.
• Events are typically used to signal user actions such as button clicks or menu selections in graphical
user interfaces.
• When an event has multiple subscribers, the event handlers are invoked synchronously when an
event is raised. To invoke events asynchronously, see Calling Synchronous Methods
Asynchronously.
• In the .NET Framework class library, events are based on the EventHandler delegate and the
EventArgs base class.
EVENT VS DELEGATE
EVENT
• Assign: +=, -= (multicast only)
• Can be included in an interface declaration
interface ITest {
event MsgHandler msgNotifier; }
• Event can only be invoked from within the
class that declared it
• Come with add and remove accessor
methods.
public event MsgHandler msgNotifier {
add { msgNotifier += value; }
}
DELEGATE
• Assign: =, +=, -=
• Cannot be included in an interface
declaration
• Can be invoked by whoever has access
to it
• No accesor method
LAMBDA EXPRESSION
ANONYMOUS METHODS
delegate void MyDelegate(int x);
MyDelegate myDel;
void Start () {
myDel = delegate { print("Yahoo"); };
myDel += delegate (int x) { print(x); };
if (myDel != null)
myDel(3);
}
ANONYMOUS METHOD REMARKS
• The scope of the parameters of an anonymous method is the anonymous-
method-block.
• It is an error to have a jump statement, such as goto, break, or continue,
inside the anonymous method block if the target is outside the block.
• It is also an error to have a jump statement, such as goto, break, or continue,
outside the anonymous method block if the target is inside the block.
• No unsafe code can be accessed within the anonymous-method-block.
• Anonymous methods are not allowed on the left side of the is operator.
ANONYMOUS METHOD REMARKS
• The local variables and parameters whose scope contains an anonymous
method declaration are called outer variables of the anonymous method.
int n = 0;
Del d = delegate() { print("Copy #:{0}", ++n); };
• A reference to the outer variable n is said to be captured when the delegate is
created.
• Unlike local variables, the lifetime of a captured variable extends until the
delegates that reference the anonymous methods are eligible for garbage
collection.
• An anonymous method cannot access the ref or out parameters of an outer
scope.
LAMBDA EXPRESSION
• An anonymous function that you can use to create delegates or expression
tree types.
• A shorthand that allows you to write a method in the same place you are
going to use it.
• Creation: You specify input parameters (if any) on the left side of the lambda
operator =>, and you put the expression or statement block on the other side.
• Syntax: Parameters => Executed code
• Example: x => x * x
LAMBDA EXPRESSION EXAMPLE
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
BENEFIT OF LAMBDA EXPRESSION
• Reduced typing. No need to specify the name of the function, its return type,
and its access modifier.
• When reading the code, you don't need to look elsewhere for the method's
definition.
TYPE INFERENCE IN LAMBDAS
• When writing lambdas, you often do not have to specify a type for the input
parameters because the compiler can infer the type.
• The general rules for lambdas are as follows:
• The lambda must contain the same number of parameters as the delegate type.
• Each input parameter in the lambda must be implicitly convertible to its corresponding
delegate parameter.
• The return value of the lambda (if any) must be implicitly convertible to the delegate's
return type.
EXPRESSION LAMBDAS
• A lambda expression with an expression on the right side of the => operator is
called an expression lambda.
• An expression lambda returns the result of the expression and takes the
following basic form: (input parameters) => expression
(x, y) => x == y
(int x, string s) => s.Length > x
() => SomeMethod()
STATEMENT LAMBDAS
• A statement lambda resembles an expression lambda except that the
statement(s) is enclosed in braces:
delegate void TestDelegate(string s);
…
TestDelegate myDel =
n => { string s = n + " " + "World"; print(s); };
myDel("Hello");
OTHER TECHNIQUES
NULL-CONDITIONAL OPERATOR (? AND ?[])
• Let’s start with null-conditional operator – it’s ?.. It’s also called ‘Elvis-
operator’. Not sure why? Have a closer look – you will see a pair of eyes with
Elvis like haircut. The operator lets you access members and elements only
when the receiver is not-null, returning null result otherwise.
int? length = people?.Length; // null if people is null
• There is also second null-conditional operator that lets you access elements
by index operator
Person first = people?[0]; // null if people is null
Type personType = people?[0].GetType(); //null if people is
null
• You can also chain null-conditional operators.
int? count = customers?[0].Orders?.Count();
NULL-CONDITIONAL DELEGATE INVOCATION
• Delegate invocation can’t immediately follow the ? operator – too many
syntactic ambiguities. Following will not work:
if (myDelegate?(args) ?? false) { … } // Won’t compile!
• However, you can call it via the Invoke method on the delegate:
if (myDelegate?.Invoke(args) ?? false) { … } // Will work fine
• Very useful way to use it is for event triggering
PropertyChanged?.Invoke(this, args);
NULL-COALESCING OPERATOR (??)
• The null-coalescing operator was designed to be used easy with null-
conditional operators. It provides default value when the outcome is null.
int length = people?.Length ?? 0; // 0 if people is null
EXTENSION METHOD
• Extension methods allow developers to add new methods to the public
contract of an existing CLR type, without having to sub-class it or recompile
the original type.
• Extension Methods help blend the flexibility of "duck typing" support popular
within dynamic languages today with the performance and compile-time
validation of strongly-typed languages.
EXAMPLE OF EXTENSION METHOD
string email = Request.QueryString["email"];
// without extension method
if ( EmailValidator.IsValid(email) ) {}
// with extension method
if ( email.IsValidEmailAddress() ) {}
...
// extension method declaration
public static class ScottGuExtensions {
public static bool IsValidEmailAddress(this string s){
Regex regex = new Regex(@"^[w-.]+@([w-]+.)+[w-]{2,4}$");
return regex.IsMatch(s);
}
}
ANOTHER EXAMPLE
PARTIAL CLASS
PARTIAL METHODS
• Signatures in both parts of the partial type must match.
• The method must return void.
• No access modifiers are allowed. Partial methods are implicitly private.
TUPLE TYPE
• Unnamed tuple:
• var unnamed = ("one", "two"); Debug.Log(unnamed.Item1);
• Named tuple:
• var named = (first: "one", second: "two"); Debug.Log(named.first);
• var sum = 12.5; var count = 5; var accumulation = (count, sum);
• Old style:
• Tuple<int, string, string> person = new Tuple <int, string, string>(1, "Steve", "Jobs");
• Anonymous types are immutable, tuples are not.
DYNAMIC TYPE
• dynamic myDynamicVar;
LINQ
ANONYMOUS TYPE
• Anonymous type, as the name suggests, is a type that doesn't have any name.
• C# allows you to create an object with the new keyword without defining its class.
• The implicitly typed variable- var is used to hold the reference of anonymous types.
var myAnonymousType = new {
firstProperty = "First",
secondProperty = 2,
thirdProperty = true
};
LINQ QUERIES
• A query is an expression that retrieves data from a data source.
• Queries are usually expressed in a specialized query language. LINQ simplifies
this situation by offering a consistent model for working with data across
various kinds of data sources and formats.
• In a LINQ query, you are always working with objects. You use the same basic
coding patterns to query and transform data in XML documents, SQL
databases, ADO.NET Datasets, .NET collections, and any other format for
which a LINQ provider is available.
THREE PARTS OF A QUERY OPERATION
1. Obtain the data source.
2. Create the query.
3. Execute the query.
THREE PARTS OF A QUERY OPERATION
using System.Linq;
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery) {
print("{0,1} ", num);
}
LINQ DATA SOURCE PART
• Queryable types: types that support IEnumerable<T> or a derived interface
such as the generic IQueryable<T> are called.
• A queryable type requires no modification or special treatment to serve as a
LINQ data source.
LINQ QUERY PART
• Specifies what information to retrieve from the data source or sources.
• Optionally, a query also specifies how that information should be sorted,
grouped, and shaped before it is returned.
• The important point is that in LINQ, the query variable itself takes no action
and returns no data. It just stores the information that is required to produce
the results when the query is executed at some later point.
LINQ QUERY PART
• A query is stored in a query variable and initialized with a query expression.
• The query expression contains three clauses:
• The from clause specifies the data source,
• The where clause applies the filter,
• The select clause specifies the type of the returned elements.
// 2. Query creation.
var numQuery = // numQuery is an IEnumerable<int>
from num in numbers
where (num % 2) == 0
select num;
QUERY EXECUTION PART
• As stated previously, the query variable itself only stores the query
commands.
• The actual execution of the query is deferred until you iterate over the query
variable in a foreach statement.
// Query execution.
foreach (int num in numQuery) {
print("{0,1} ", num);
}
• Because the query variable itself never holds the query results, you can
execute it as often as you like.
FORCING IMMEDIATE EXECUTION
• Queries that perform aggregation functions (Count, Max, Average, and First)
over a range of source elements must first iterate over those elements.
• These execute without an explicit foreach statement because the query itself
must use foreach in order to return a result.
var evenNumQuery =
from num in numbers
where (num % 2) == 0
select num;
int evenNumCount = evenNumQuery.Count();
• To force immediate execution of any query and cache its results, you can call
the ToList<TSource> or ToArray<TSource> methods.
QUERY SYNTAX AND METHOD SYNTAX
• Most queries in the introductory Language Integrated Query (LINQ)
documentation are written by using the LINQ declarative query syntax.
• However, the query syntax must be translated into method calls for the .NET
common language runtime (CLR) when the code is compiled.
• These method calls invoke the standard query operators, which have names
such as Where, Select, GroupBy, Join, Max, and Average.
• You can call them directly by using method syntax instead of query syntax.
QUERY SYNTAX AND METHOD SYNTAX
//Query syntax:
IEnumerable<int> numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;
//Method syntax:
IEnumerable<int> numQuery2 =
numbers.Where(num => num % 2 == 0).OrderBy(n => n);
LAMBDA EXPRESSION IN QUERY
• You do not use lambda expressions directly in query syntax, but you do use
them in method calls, and query expressions can contain method calls.
• In fact, some query operations can only be expressed in method syntax.
// Data source.
int[] scores = { 90, 71, 82, 93, 75, 82 };
// The call to Count forces iteration of the source
int highScoreCount = scores.Where(n => n > 80).Count();
• Note that the Where method in this example has an input parameter of the
delegate type Func<T, TResult> and that delegate takes an integer as input
and returns a Boolean.
REFERENCES
• Using threads with Unity, The Knights of Unity (http://blog.theknightsofunity.com/using-threads-unity/)
• Myths and Facts of the Unity Game Engine, The Knights of Unity (http://blog.theknightsofunity.com/myths-
and-facts-of-unity-game-engine/)
• Iterators (C#), Microsoft Developer Network, 20 July 2015 (https://msdn.microsoft.com/en-
us/library/mt639331.aspx)
• Coroutines: Building a framework in C#, Net Gnome, 12 Feb 2014
(https://www.gamedev.net/blog/1612/entry-2259253-coroutines-building-a-framework-in-c/)
• Coroutine++, Unity Gems, 27 Jan 2016, (https://unitygem.wordpress.com/2016/01/27/coroutine/)
• Mastering Coroutines in Unity in 10 mins, Rudra Gesota , 14 July 201,
(http://www.theappguruz.com/blog/how-to-use-coroutines-in-unity)
• Coroutines – More than you want to know, horseman, 26 Aug 2012
(http://twistedoakstudios.com/blog/Post83_coroutines-more-than-you-want-to-know)
REFERENCES
• Anonymous Methods (C# Programming Guide), Microsoft Developer Network, 20 Jul 2015
(https://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx)
• Using Variance in Delegates (C#), Microsoft Developer Network, 20 Jul 2015 (https://msdn.microsoft.com/en-
us/library/mt654057.aspx)
• Using Variance for Func and Action Generic Delegates (C#), Microsoft Developer Network, July 20, 2015
(https://msdn.microsoft.com/en-us/library/mt654054.aspx)
• Events (C# Programming Guide) , Microsoft Developer Network, Jul 20, 2015 (https://msdn.microsoft.com/en-
us/library/awbftdfh.aspx)
• C# events vs. delegates, Julien Couvreur, 29 Apr 2003 (http://blog.monstuff.com/archives/000040.html)
• Understand Lambda Expressions in 3 Minutes, Dan Avidar, 5 Mar 2013
(https://www.codeproject.com/tips/298963/understand-lambda-expressions-in-minutes)
• Lambda Expressions (C# Programming Guide), Microsoft Developer Network, Jul 20, 2015
(https://msdn.microsoft.com/en-us/library/bb397687.aspx)
• C# Anonymous Type, Tutorials Teacher (http://www.tutorialsteacher.com/csharp/csharp-anonymous-type)
• Introduction to LINQ Queries (C#), Microsoft Developer Network, Jul 20, 2015
(https://msdn.microsoft.com/en-us/library/bb397906.aspx)
• Lesson 01: Introduction to LINQ, Joe Mayo (http://csharp-station.com/Tutorial/Linq/Lesson01)
• How to: Use Lambda Expressions in a Query (C# Programming Guide), Microsoft Developer Network, Jul 20,
2015 (https://msdn.microsoft.com/en-us/library/bb397675.aspx)
• Query Syntax and Method Syntax in LINQ (C#), Microsoft Developer Network, Jul 20, 2015
(https://msdn.microsoft.com/en-us/library/bb397947.aspx)

Weitere ähnliche Inhalte

Was ist angesagt?

OTcl and C++ linkages in NS2
OTcl and C++ linkages in NS2OTcl and C++ linkages in NS2
OTcl and C++ linkages in NS2Pradeep Kumar TS
 
VHDL PROGRAMS FEW EXAMPLES
VHDL PROGRAMS FEW EXAMPLESVHDL PROGRAMS FEW EXAMPLES
VHDL PROGRAMS FEW EXAMPLESkarthik kadava
 
The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202Mahmoud Samir Fayed
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in GeckoChih-Hsuan Kuo
 
Virtual platform
Virtual platformVirtual platform
Virtual platformsean chen
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
C# Advanced L04-Threading
C# Advanced L04-ThreadingC# Advanced L04-Threading
C# Advanced L04-ThreadingMohammad Shaker
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approachAlexander Granin
 
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Neeraj Kaushik
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189Mahmoud Samir Fayed
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSOswald Campesato
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 

Was ist angesagt? (19)

OTcl and C++ linkages in NS2
OTcl and C++ linkages in NS2OTcl and C++ linkages in NS2
OTcl and C++ linkages in NS2
 
VHDL PROGRAMS FEW EXAMPLES
VHDL PROGRAMS FEW EXAMPLESVHDL PROGRAMS FEW EXAMPLES
VHDL PROGRAMS FEW EXAMPLES
 
Completable future
Completable futureCompletable future
Completable future
 
Os2
Os2Os2
Os2
 
The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202The Ring programming language version 1.8 book - Part 88 of 202
The Ring programming language version 1.8 book - Part 88 of 202
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
Virtual platform
Virtual platformVirtual platform
Virtual platform
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Interaksi obyek
Interaksi obyekInteraksi obyek
Interaksi obyek
 
C# Advanced L04-Threading
C# Advanced L04-ThreadingC# Advanced L04-Threading
C# Advanced L04-Threading
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approach
 
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 

Ähnlich wie CSharp for Unity Day2

History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel ZikmundKarel Zikmund
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовYandex
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel GeheugenDevnology
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовYandex
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 

Ähnlich wie CSharp for Unity Day2 (20)

Thread
ThreadThread
Thread
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
 
Microkernel Development
Microkernel DevelopmentMicrokernel Development
Microkernel Development
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 

Kürzlich hochgeladen

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Kürzlich hochgeladen (20)

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

CSharp for Unity Day2

  • 1. C# FOR UNITY - ADVANCE TECHNIQUE PRESENTER: DUONG HOANG THANH
  • 2. CONTENTS • Multithreading • Iterator • Co-routine • Delegate • Event • Lambda • Other Techniques • LINQ
  • 4. C# THREAD void MethodA() { for (int i = 0; i < 100; i++) Console.Write("0"); } … Thread t = new Thread(MethodA); t.Start();
  • 5. YOU CANNOT SPAWN THREADS IN UNITY ? • It’s a myth. Many people are confusing Unity coroutines with threads. • Let’s get this straight: Coroutines have nothing to do with threads. • Coroutine is only a way to delay code execution without too much effort. • It’s really a great method of writing game code when some routines are needed to be executed in sequence over a time (like animations), • but everything is still done in a single thread.
  • 7. WHEN THREADS ARE BAD • Threads are dangerous, so you must be very careful when synchronizing things back. • You also need to remember that Unity API is not thread safe, so all calls to Unity API should be done from the main thread.
  • 8. WHEN THREADS ARE GOOD • When you’re computing some expensive and/or long-term operations. Like: • AI • Pathfinding • Network communication • Files operations
  • 10. WHAT IS ITERATOR • An iterator is a method, get accessor, or operator that performs a custom iteration over an array or collection class by using the yield keyword. • The yield return statement causes an element in the source sequence to be returned immediately to the caller before the next element in the source sequence is accessed. • Although you write an iterator as a method, the compiler translates it into a nested class that is, in effect, a state machine. This class keeps track of the position of the iterator as long the foreach loop on the client code continues.
  • 11. ITERATORS OVERVIEW • Is a section of code that returns an ordered sequence of values of the same type. • Can be used as the body of a method, an operator, or a get accessor. • yield return statement to return each element in turn. • yield break ends the iteration. • Multiple iterators can be implemented on a class. foreach(int x in SampleClass.Iterator2){} • Return type must be IEnumerable, IEnumerator, IEnumerable<T>, or IEnumerator<T>. • Are the basis for the deferred execution behavior in LINQ queries.
  • 12. ITERATOR EXAMPLE public class DaysOfTheWeek : System.Collections.IEnumerable { string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" }; public System.Collections.IEnumerator GetEnumerator() { for (int i = 0; i < days.Length; i++) { yield return days[i]; } } } … DaysOfTheWeek week = new DaysOfTheWeek(); // Iterate with foreach foreach (string day in week) { System.Console.Write(day + " "); }
  • 13. HOW DOES FOREACH WORK? public void do_stuff() { IEnumerator foo = bar.GetEnumerator(); foo.MoveNext(); print(foo.Current);//print 1 to console foo.MoveNext(); print(foo.Current);//print 5 to console } public IEnumerable<int> bar(){ yield return 1; yield return 5; }
  • 14. COROUTINE IS AN ITERATOR public IEnumerator InternalRoutine(IEnumerator coroutine){ while(true){ if(!coroutine.MoveNext()){ yield break; } object yielded = coroutine.Current; Debug.Log(yielded); yield return coroutine.Current; } }
  • 16. COROUTINE • A special type of function used in Unity • to stop the execution until sometime or certain condition is met, • and continues from where it had left off. • It is essentially a function declared with a return type of IEnumerator • and with the yield return statement included somewhere in the body. • The yield return line is the point at which execution will pause and be resumed the following frame
  • 17. START & STOP COROUTINE • The start of a coroutine corresponds to the creation of an object of type coroutine. public Coroutine StartCoroutine(string methodName, object value = null); public void StopCoroutine(string methodName); public Coroutine StartCoroutine(IEnumerator routine); public void StopCoroutine(IEnumerator routine); public void StopAllCoroutines(); IEnumerator MyCoroutine(){yield return null;} IEnumerator MyCoroutineOneParam(int i){yield return null;} IEnumerator MyCoroutineManyParams(int i, int j){yield return null;}
  • 18. COROUTINE UPDATE Coroutine is tied to the MonoBehaviour component that hosted the call.
  • 19. EXAMPLEvoid Start() { print("Start method"); StartCoroutine(TestCoroutine()); print("Start method ends"); } IEnumerator TestCoroutine() { print("TestCoroutine"); while(true) { print("Here"); yield return null; print("There"); } } void Update(){print("Update");} • It logs as: Start method TestCoroutine Here Start method ends Update There Here Update There Here
  • 20. DESTROY GAME OBJECT WILL STOP COROUTINE void OnCollisionEnter(Collision col) { if(col.gameObject.CompareTag("Rocket")) { StartCoroutine(Explosion()); Destroy(this.gameObject); } }
  • 21. WHAT YOU CAN YIELD • null – the coroutine executes the next time that it is eligible • WaitForEndOfFrame – the coroutine executes on the frame, after all of the rendering and GUI is complete • WaitForFixedUpdate – causes this coroutine to execute at the next physics step, after all physics is calculated • WaitForSeconds – causes the coroutine not to execute for a given game time period • WWW – waits for a web request to complete (resumes as if WaitForSeconds or null) • Another coroutine – in which case the new coroutine will run to completion before the yielder is resumed • yield break – immediately stops the coroutine. • …
  • 22. CONVERT TO COROUTINE • Auto called methods of MonoBehaviour that return IEnumerator will be treated as Coroutine • But can we stop them by StopCoroutine ? private IEnumerator Start() { Debug.Log("Start method"); yield return StartCoroutine(TestCoroutine()); Debug.Log("Start method ends"); }
  • 23. WHAT’S WRONG? private IEnumerator Start() { Debug.Log("Start method"); yield return StartCoroutine(TestCoroutine()); Debug.Log("Start method ends"); } private IEnumerator Start() { Debug.Log("Start method"); yield return (TestCoroutine()); Debug.Log("Start method ends"); }
  • 24. DOWNLOAD ITEM private IEnumerator DownloadItem(string url, Action callback) { if(string.IsNullOrEmpty(url)) yield break; // wrong url, stop the coroutine WWW www = new WWW(url); // Start the downloading yield return www; // Wait for the end of the downloading if(www.error != null){ // Something went wrong // Handle error yield break; } // Take care of the www object if(callback != null) { callback (); } }
  • 25. WAITING FOR THE END OF A DOWNLOADING private IEnumerator Start() { DisplayUIMessage("Loading..."); yield return StartCoroutine(DownloadItem(url, StartLevel)); } private void StartLevel(){ // Set UI Off // start level }
  • 26. COROUTINE SUMMARY • Coroutines are a really good way of making a sequence of operations happen over time or when some external process is completed • Coroutines are not threads and are not asynchronous • Nothing else is running when your coroutine is executing • Your coroutine will resume when the conditions of your yield statement are met • Coroutines are inactive when the script is disabled or the object is destroyed • yield return new WaitForSeconds is dependent on game time which is affected by Time.timeScale
  • 28. DELEGATE • A type that represents references to methods with a particular parameter list and return type. public delegate int PerformCalculation(int x, int y); • When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. • You can call the method through the delegate instance.
  • 29. USING DELEGATE public class DelegateScript : MonoBehaviour { delegate void MyDelegate(int num); MyDelegate myDelegate; void Start () { myDelegate = PrintNum; myDelegate(50); } void PrintNum(int num) { print ("Print Num: " + num); }
  • 30. DELEGATE OVERVIEW • Are like C++ function pointers but are type safe. • Allow methods to be passed as parameters. • Can be used to define callback methods. • Can be chained together; for example, multiple methods can be called on a single event. • Methods do not have to match the delegate type exactly.
  • 31. DELEGATE AS CALLBACK public class DelegateScript : MonoBehaviour { delegate void UpdateHandler(); public UpdateHandler onUpdate; void Update () { if (onUpdate != null) { onUpdate(); } }
  • 32. ACTION DELEGATE namespace System { public delegate void Action(); public delegate void Action<T>(T obj); public delegate void Action<T1, T2>(T1 arg1, T2 arg2); public delegate void Action<T1, T2, T3>( T1 arg1, T2 arg2 , T2 arg3); public delegate void Action<T1, T2, T3, T4>( T1 arg1, T2 arg2 , T2 arg3 , T2 arg4); }
  • 33. FUNC DELEGATE namespace System { public delegate TResult Func<TResult>(); public delegate TResult Func<T, TResult>(T arg1); public delegate TResult Func<T1, T2, TResult>(T arg1, T arg2); public delegate TResult Func<T1, T2, T3, TResult>( T arg1, T arg2, T arg3); public delegate TResult Func<T1, T2, T3, T4, TResult>( T arg1, T arg2, T arg3, T arg4); }
  • 34. USING VARIANCE IN DELEGATES • When you assign a method to a delegate, covariance and contravariance provide flexibility for matching a delegate type with a method signature. • Covariance permits a method to have return type that is more derived than that defined in the delegate. • Contravariance permits a method that has parameter types that are less derived than those in the delegate type.
  • 35. COVARIANCE class Mammals{} class Dogs : Mammals{} class Program { public delegate Mammals HandlerMethod(); public static Mammals MammalsHandler() { return null; } public static Dogs DogsHandler() { return null; } static void Test() { HandlerMethod handlerMammals = MammalsHandler; // Covariance enables this assignment. HandlerMethod handlerDogs = DogsHandler; } }
  • 36. CONTRAVARIANCE public delegate void Action<in T>(T obj) public class Person { } public class Employee : Person { } class Program { static void AddToContacts(Person person) { } static void Test() { Action<Person> addPersonToContacts = AddToContacts; // Contravariance enables those assignments. Action<Employee> addEmployeeToContacts = AddToContacts; addEmployeeToContacts = addPersonToContacts; } }
  • 38. EVENTS • Events enable a class or object to notify other classes or objects when something of interest occurs. • The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. • Events in the .NET Framework are based on the delegate model. The delegate model follows the observer design pattern, which enables a subscriber to register with, and receive notifications from, a provider.
  • 39. DECLARE & USE EVENT delegate void MsgHandler(string s); class Class1 { public static event MsgHandler msgNotifier; static void Main(string[] args) { Class1.msgNotifier += new MsgHandler(PipeNull); Class1.msgNotifier("test"); } static void PipeNull(string s) { return; } }
  • 40. EVENTS OVERVIEW • The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event. • An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers. • Events that have no subscribers are never raised. • Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces. • When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events asynchronously, see Calling Synchronous Methods Asynchronously. • In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.
  • 41. EVENT VS DELEGATE EVENT • Assign: +=, -= (multicast only) • Can be included in an interface declaration interface ITest { event MsgHandler msgNotifier; } • Event can only be invoked from within the class that declared it • Come with add and remove accessor methods. public event MsgHandler msgNotifier { add { msgNotifier += value; } } DELEGATE • Assign: =, +=, -= • Cannot be included in an interface declaration • Can be invoked by whoever has access to it • No accesor method
  • 43. ANONYMOUS METHODS delegate void MyDelegate(int x); MyDelegate myDel; void Start () { myDel = delegate { print("Yahoo"); }; myDel += delegate (int x) { print(x); }; if (myDel != null) myDel(3); }
  • 44. ANONYMOUS METHOD REMARKS • The scope of the parameters of an anonymous method is the anonymous- method-block. • It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block if the target is outside the block. • It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block if the target is inside the block. • No unsafe code can be accessed within the anonymous-method-block. • Anonymous methods are not allowed on the left side of the is operator.
  • 45. ANONYMOUS METHOD REMARKS • The local variables and parameters whose scope contains an anonymous method declaration are called outer variables of the anonymous method. int n = 0; Del d = delegate() { print("Copy #:{0}", ++n); }; • A reference to the outer variable n is said to be captured when the delegate is created. • Unlike local variables, the lifetime of a captured variable extends until the delegates that reference the anonymous methods are eligible for garbage collection. • An anonymous method cannot access the ref or out parameters of an outer scope.
  • 46. LAMBDA EXPRESSION • An anonymous function that you can use to create delegates or expression tree types. • A shorthand that allows you to write a method in the same place you are going to use it. • Creation: You specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. • Syntax: Parameters => Executed code • Example: x => x * x
  • 47. LAMBDA EXPRESSION EXAMPLE delegate int del(int i); static void Main(string[] args) { del myDelegate = x => x * x; int j = myDelegate(5); //j = 25 }
  • 48. BENEFIT OF LAMBDA EXPRESSION • Reduced typing. No need to specify the name of the function, its return type, and its access modifier. • When reading the code, you don't need to look elsewhere for the method's definition.
  • 49. TYPE INFERENCE IN LAMBDAS • When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type. • The general rules for lambdas are as follows: • The lambda must contain the same number of parameters as the delegate type. • Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter. • The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.
  • 50. EXPRESSION LAMBDAS • A lambda expression with an expression on the right side of the => operator is called an expression lambda. • An expression lambda returns the result of the expression and takes the following basic form: (input parameters) => expression (x, y) => x == y (int x, string s) => s.Length > x () => SomeMethod()
  • 51. STATEMENT LAMBDAS • A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces: delegate void TestDelegate(string s); … TestDelegate myDel = n => { string s = n + " " + "World"; print(s); }; myDel("Hello");
  • 53. NULL-CONDITIONAL OPERATOR (? AND ?[]) • Let’s start with null-conditional operator – it’s ?.. It’s also called ‘Elvis- operator’. Not sure why? Have a closer look – you will see a pair of eyes with Elvis like haircut. The operator lets you access members and elements only when the receiver is not-null, returning null result otherwise. int? length = people?.Length; // null if people is null • There is also second null-conditional operator that lets you access elements by index operator Person first = people?[0]; // null if people is null Type personType = people?[0].GetType(); //null if people is null • You can also chain null-conditional operators. int? count = customers?[0].Orders?.Count();
  • 54. NULL-CONDITIONAL DELEGATE INVOCATION • Delegate invocation can’t immediately follow the ? operator – too many syntactic ambiguities. Following will not work: if (myDelegate?(args) ?? false) { … } // Won’t compile! • However, you can call it via the Invoke method on the delegate: if (myDelegate?.Invoke(args) ?? false) { … } // Will work fine • Very useful way to use it is for event triggering PropertyChanged?.Invoke(this, args);
  • 55. NULL-COALESCING OPERATOR (??) • The null-coalescing operator was designed to be used easy with null- conditional operators. It provides default value when the outcome is null. int length = people?.Length ?? 0; // 0 if people is null
  • 56. EXTENSION METHOD • Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. • Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.
  • 57. EXAMPLE OF EXTENSION METHOD string email = Request.QueryString["email"]; // without extension method if ( EmailValidator.IsValid(email) ) {} // with extension method if ( email.IsValidEmailAddress() ) {} ... // extension method declaration public static class ScottGuExtensions { public static bool IsValidEmailAddress(this string s){ Regex regex = new Regex(@"^[w-.]+@([w-]+.)+[w-]{2,4}$"); return regex.IsMatch(s); } }
  • 60. PARTIAL METHODS • Signatures in both parts of the partial type must match. • The method must return void. • No access modifiers are allowed. Partial methods are implicitly private.
  • 61. TUPLE TYPE • Unnamed tuple: • var unnamed = ("one", "two"); Debug.Log(unnamed.Item1); • Named tuple: • var named = (first: "one", second: "two"); Debug.Log(named.first); • var sum = 12.5; var count = 5; var accumulation = (count, sum); • Old style: • Tuple<int, string, string> person = new Tuple <int, string, string>(1, "Steve", "Jobs"); • Anonymous types are immutable, tuples are not.
  • 62. DYNAMIC TYPE • dynamic myDynamicVar;
  • 63. LINQ
  • 64. ANONYMOUS TYPE • Anonymous type, as the name suggests, is a type that doesn't have any name. • C# allows you to create an object with the new keyword without defining its class. • The implicitly typed variable- var is used to hold the reference of anonymous types. var myAnonymousType = new { firstProperty = "First", secondProperty = 2, thirdProperty = true };
  • 65. LINQ QUERIES • A query is an expression that retrieves data from a data source. • Queries are usually expressed in a specialized query language. LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats. • In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ provider is available.
  • 66. THREE PARTS OF A QUERY OPERATION 1. Obtain the data source. 2. Create the query. 3. Execute the query.
  • 67. THREE PARTS OF A QUERY OPERATION using System.Linq; // 1. Data source. int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; // 2. Query creation. var numQuery = from num in numbers where (num % 2) == 0 select num; // 3. Query execution. foreach (int num in numQuery) { print("{0,1} ", num); }
  • 68. LINQ DATA SOURCE PART • Queryable types: types that support IEnumerable<T> or a derived interface such as the generic IQueryable<T> are called. • A queryable type requires no modification or special treatment to serve as a LINQ data source.
  • 69. LINQ QUERY PART • Specifies what information to retrieve from the data source or sources. • Optionally, a query also specifies how that information should be sorted, grouped, and shaped before it is returned. • The important point is that in LINQ, the query variable itself takes no action and returns no data. It just stores the information that is required to produce the results when the query is executed at some later point.
  • 70. LINQ QUERY PART • A query is stored in a query variable and initialized with a query expression. • The query expression contains three clauses: • The from clause specifies the data source, • The where clause applies the filter, • The select clause specifies the type of the returned elements. // 2. Query creation. var numQuery = // numQuery is an IEnumerable<int> from num in numbers where (num % 2) == 0 select num;
  • 71. QUERY EXECUTION PART • As stated previously, the query variable itself only stores the query commands. • The actual execution of the query is deferred until you iterate over the query variable in a foreach statement. // Query execution. foreach (int num in numQuery) { print("{0,1} ", num); } • Because the query variable itself never holds the query results, you can execute it as often as you like.
  • 72. FORCING IMMEDIATE EXECUTION • Queries that perform aggregation functions (Count, Max, Average, and First) over a range of source elements must first iterate over those elements. • These execute without an explicit foreach statement because the query itself must use foreach in order to return a result. var evenNumQuery = from num in numbers where (num % 2) == 0 select num; int evenNumCount = evenNumQuery.Count(); • To force immediate execution of any query and cache its results, you can call the ToList<TSource> or ToArray<TSource> methods.
  • 73. QUERY SYNTAX AND METHOD SYNTAX • Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using the LINQ declarative query syntax. • However, the query syntax must be translated into method calls for the .NET common language runtime (CLR) when the code is compiled. • These method calls invoke the standard query operators, which have names such as Where, Select, GroupBy, Join, Max, and Average. • You can call them directly by using method syntax instead of query syntax.
  • 74. QUERY SYNTAX AND METHOD SYNTAX //Query syntax: IEnumerable<int> numQuery1 = from num in numbers where num % 2 == 0 orderby num select num; //Method syntax: IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);
  • 75. LAMBDA EXPRESSION IN QUERY • You do not use lambda expressions directly in query syntax, but you do use them in method calls, and query expressions can contain method calls. • In fact, some query operations can only be expressed in method syntax. // Data source. int[] scores = { 90, 71, 82, 93, 75, 82 }; // The call to Count forces iteration of the source int highScoreCount = scores.Where(n => n > 80).Count(); • Note that the Where method in this example has an input parameter of the delegate type Func<T, TResult> and that delegate takes an integer as input and returns a Boolean.
  • 76. REFERENCES • Using threads with Unity, The Knights of Unity (http://blog.theknightsofunity.com/using-threads-unity/) • Myths and Facts of the Unity Game Engine, The Knights of Unity (http://blog.theknightsofunity.com/myths- and-facts-of-unity-game-engine/) • Iterators (C#), Microsoft Developer Network, 20 July 2015 (https://msdn.microsoft.com/en- us/library/mt639331.aspx) • Coroutines: Building a framework in C#, Net Gnome, 12 Feb 2014 (https://www.gamedev.net/blog/1612/entry-2259253-coroutines-building-a-framework-in-c/) • Coroutine++, Unity Gems, 27 Jan 2016, (https://unitygem.wordpress.com/2016/01/27/coroutine/) • Mastering Coroutines in Unity in 10 mins, Rudra Gesota , 14 July 201, (http://www.theappguruz.com/blog/how-to-use-coroutines-in-unity) • Coroutines – More than you want to know, horseman, 26 Aug 2012 (http://twistedoakstudios.com/blog/Post83_coroutines-more-than-you-want-to-know)
  • 77. REFERENCES • Anonymous Methods (C# Programming Guide), Microsoft Developer Network, 20 Jul 2015 (https://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx) • Using Variance in Delegates (C#), Microsoft Developer Network, 20 Jul 2015 (https://msdn.microsoft.com/en- us/library/mt654057.aspx) • Using Variance for Func and Action Generic Delegates (C#), Microsoft Developer Network, July 20, 2015 (https://msdn.microsoft.com/en-us/library/mt654054.aspx) • Events (C# Programming Guide) , Microsoft Developer Network, Jul 20, 2015 (https://msdn.microsoft.com/en- us/library/awbftdfh.aspx) • C# events vs. delegates, Julien Couvreur, 29 Apr 2003 (http://blog.monstuff.com/archives/000040.html) • Understand Lambda Expressions in 3 Minutes, Dan Avidar, 5 Mar 2013 (https://www.codeproject.com/tips/298963/understand-lambda-expressions-in-minutes)
  • 78. • Lambda Expressions (C# Programming Guide), Microsoft Developer Network, Jul 20, 2015 (https://msdn.microsoft.com/en-us/library/bb397687.aspx) • C# Anonymous Type, Tutorials Teacher (http://www.tutorialsteacher.com/csharp/csharp-anonymous-type) • Introduction to LINQ Queries (C#), Microsoft Developer Network, Jul 20, 2015 (https://msdn.microsoft.com/en-us/library/bb397906.aspx) • Lesson 01: Introduction to LINQ, Joe Mayo (http://csharp-station.com/Tutorial/Linq/Lesson01) • How to: Use Lambda Expressions in a Query (C# Programming Guide), Microsoft Developer Network, Jul 20, 2015 (https://msdn.microsoft.com/en-us/library/bb397675.aspx) • Query Syntax and Method Syntax in LINQ (C#), Microsoft Developer Network, Jul 20, 2015 (https://msdn.microsoft.com/en-us/library/bb397947.aspx)