Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# for Unity3D Yingcai Xiao.

Similar presentations


Presentation on theme: "C# for Unity3D Yingcai Xiao."— Presentation transcript:

1 C# for Unity3D Yingcai Xiao

2 Unity3D & C# Unity uses two programming languages for coding animation scripts: JavaScript and C# JavaScript for simple animations, no support of OOP nor EDP. C# for sophisticated animations, supports OOP & EDP, platform independent.

3 C# References http://www.learncs.org/

4 Part I Moving from C++/Java to C#

5 Data Types in (CTS) Primitives (int, float, …)
System-defined Types (SDTs): Primitives (int, float, …) User-defined Types (UDTs): Classes Properties Structs Interfaces Enumerations Events Delegates Generics Templates

6 Classes Class: a group of code and data to be instantiated to form objects. Four categories of class members: Fields: member variables Methods: member functions Properties: fields exposed using accessor (get and set) methods Events: notifications a class is capable of firing

7 Example: How to define a class (user-defined data type)
class Rectangle { // Fields protected int width = 1; protected int height = 1; // Methods public Rectangle () { } public Rectangle (int cx, int cy) width = cx; height = cy; }

8 Example: How to define a class (user-defined data type)
// Accessor Methods public void setWidth(int w) { width = w; } public int getWidth() { return width; } public void setHeight(int h) { height = h; } public int getHeight() { return height; } public int area() { int a; a = height*width; return a; } // End of Rectangle class

9 Example: How to use a class (user-defined data type)
Rectangle rect = new Rectangle(2,4); rect.setHeight(8); rect.setWidth(rect.getWidth() * 2); double darea = (double) rect.area();

10 Differences between C++ & C#
Ending a block with a semicolon Class myClass{ }; } Object instance creation myClass myObject; //myObject is an instance myClass *myPointer = new myClass(); //myPointer is a pointer to an instance myClass myReference //myReference is a reference (an internal pointer) to an instance Dereferencing myPointer-> myReference. Class members Fields: member variables Methods: member functions Properties: fields exposed using accessor (get and set) methods Events: notifications a class is capable of firing Freeing heap memory free(myPointer); Automatically by garbage collection when myReference is out of extent.

11 Internal Memory Structures of Data Store

12 What is Data Type? 8 Data types describe the memory layout of objects.
The name of an object is the name of the memory space stores its data value. For example, int i = 8; “i” is the name of the memory space for storing the data value 8. i 8

13 C++ Pointer 0x12345678 int width int height Rectangle ()
A pointer in C++ is a memory location that stores an address. Rectangle *rect = new Rectangle (3, 4);  rect 0x int width int height Rectangle () Rectangle (int w, int h) Area () 3 4 0x Dereferencing rect-> int area = rect->Area(); Please note the notation difference between a “pointer/reference” and a “name” in this lecture.

14 C++ Function Pointer 0x01234567 a = height*width; return a;
A method is a (function) pointer that points to the code location of the method in the “text” memory, i.e., the pointer stores the address of the code location of the method in the “text” memory. Area 0x a = height*width; return a; 0x (text memory)

15 Instantiating a Class (in CTS & C#)
Class Name; In CTS: “Rectangle rect” declares a reference of class Rectangle. A reference to a Rectangle object. rect “rect” is the name of a memory space that stores a reference. This is similar to Java. A “reference” is an internal pointer, it needs to “point” to an object before being dereferenced.

16 References in C# 0x12345678 int width int height Rectangle ()
Rectangle rect = new Rectangle (3, 4); // Use the second constructor rect 0x int width int height Rectangle () Rectangle (int w, int h) Area () 3 4 0x Dereferencing int area = rect.Area();

17 The “Object” class The root class of all other classes.
So, an object of any class is an “Object” So we can write: Object obj = new Rectangle (3, 4);  Constructor: Object () String output: ToString() Read matadata: GetType() Clean up: Finalize()

18 The Object Class: System.Object
System.Object : root class for all other classes. Every class inherits the Finalize( ) method from System.Object. It is called just before an object is destroyed by the garbage collector of CLR. The time of call is determined by CLR not by the program. Use System.GC.Collect() to force a garbage collection (system wide, time consuming). Destructor in C++ is called just before an object is destroyed by the program, when the object is freed (for heap objects) or out of scope (for stack objects).

19 C# Part II Beyond C++/Java

20 Property Can we make the member fields secure and easy to use at the same time? Eve starts here, 6/18/2016

21 Encapsulation and convenience
We protected member fields: width and height. (Encapsulation) (1) Securer code. Methods not belonging to the class hierarchy can’t access protected members. If we don’t want anyone change the value of “width”, we just don’t provide the setWidth() method. (2) Easier to maintain the code. We can rename “width” to “w” without impacting the users of the “Rectangle” class. (3) Tedious to implement and use. If we define the member fields as public, the usage would be much easier. rect.width *= 2;

22 Example: Accessor Methods for Protected Fields
class Rectangle { // Fields protected int width = 1; protected int height = 1; // Methods public Rectangle () { } public Rectangle (int cx, int cy) width = cx; height = cy; }

23 Example: How to define a class (user-defined data type)
// Accessor Methods public void setWidth(int w) { width = w; } public int getWidth() { return width; } public void setHeight(int h) { height = h; } public int getHeight() { return height; } } // End of Rectangle class

24 Example: How to use a class (user-defined data type)
Rectangle rect = new Rectangle(2,4); rect.setHeight(8); rect.setWidth(rect.getWidth() * 2); double darea = (double) (rect.getWidth() * rect.getHeight() );

25 A new construct in C# named “Property” makes member fields secure and
easy to access at the same time.

26 Example: How to define properties
// Properties defined as grouped accessor methods // in the Rectangle class public int Width // group name { get { return width; } set // the input parameter is implicit: value if (value > 0) width = value; else throw new ArgumentOutOfRangeException ( "Width must be 1 or higher"); }

27 Example: How to define properties
public int Height // a field defined by type and accessor code { get { return height; } set if (value > 0) height = value; else throw new ArgumentOutOfRangeException ( "Height must be 1 or higher"); }

28 Example: How to define properties
public int Area // a property of only get method { get { return width * height; } }

29 Properties are defined in the following format:
Defining Properties Properties are defined in the following format: protected type field-name; public type property-name { get { /* return the field value */ } set { /* reset the field value */ } } A property definition is composed of a protected or private field a property to expose the field which in turn consists of at least one accessor (get()/set()).

30 Using Properties Properties are used the same way as public fields. Rectangle rect = new Rectangle(2,4); rect.Width = 7; rect.Width *= 2; // Double the rectangle's width int area = rect.Area; // Get the rectangle's new area //Typecast a property “value” from int to double double darea = (double) rect.Area; Advantage of Properties: allow users to access private/protected fields as if they were public fields.

31 Notes on Properties Properties are public methods (set and get) used like fields. Data is secured (encapsulated) and access is simplified. (2) The set and get methods are called accessors. A property may not have the set (read-only properties) or the get (write-only properties), but can not miss both. (3) The implicit input argument, value, for the set method has the same type as the property. (4) The type of a property must be the same as the type of the field member it protects. (5) A property can’t be overloaded, e.g., we can’t define a “public double Area { … }” after defining “public int Area { … }”. You have to use a different property name, e.g. doubleArea, to define the area property of type double.

32 Why we have to name properties of different types differently?
Signature of a method: name, number of arguments, types of the arguments. Return type is not part of the signature. Overloading: two or more methods have the same name but different arguments. Name Mangling encodes the name of an overloaded method with its signature (by the compiler). The internal names of the methods are unique (no internal overloading). Property do not have any arguments, so the only way to differentiate properties of different type is by their names.

33 Internal Memory Structures of Reference & Value Types
Eve ended here, 2/18/2016

34 Instantiating a Class (in C++)
Class Name; In C++: “Rectangle rect” declares an object of class Rectangle. int width; int height; Rectangle () Rectangle (int w, int h) rect “rect” is the name of a memory space that stores a Rectangle object.

35 Instantiating a Class (in CTS)
Class Name; In CTS: “Rectangle rect” declares a reference of class Rectangle. A reference to a Rectangle object. rect “rect” is the name of a memory space that stores a reference. This is similar to Java. A “reference” is an internal pointer, it needs to “point” to an object before being dereferenced.

36 References 0x12345678 3 4 Rectangle () Rectangle (int cx, int cy) Area
Rectangle rect;  int area = rect.Area; // will not compile in C# Rectangle rect = new Rectangle (3, 4); // Use the second constructor rect 0x 3 4 Rectangle () Rectangle (int cx, int cy) Area int width Int height Rectangle () Rectangle (int w, int h) Area 0x Dereferencing is automatic for a reference. (No *rect or rect->) int area = rect.Area; Please note the notation difference between a “pointer/reference” and a “name” in this lecture.

37 Value Types int i; In CTS: is i a reference to an integer or just an integer? In CTS: i is an int (a system defined primitive type), not a reference to an integer. “i” is the name of a memory space that stores an integer value. int i = 8; i is a value type, for which we can directly store an integer value into the memory named as i. Compiler already allocated memory to store the value and we don’t need to “new” to allocate memory to store the value. i 8

38 Value Types Fields of value types have the object (not reference) memories allocated by the compiler and can be used as an object directly without “new”. Can we define user types behave like value types? Class is used to define user types, but need to be “new”ed before using. Memories are allocated at runtime. => Tedious and Slow.

39 Structs Structs: user-defined value types, less overhead and easier to use than classes. struct Point { public int x; public int y; public Point () {x = 0 ; y = 0; } public Point (int x, int y) { this.x = x; this.y = y; } } Point pnt1; // pnt1 is an object, not a reference. x = 0, y = 0 Point pnt2= new Point (); // pnt2 is an object, not a reference. x = 0, y = 0 Point pnt3 = new Point (3, 4); // pnt3 is an object, not a reference. x = 3, y = 4 // The compiler uses “new” to initialize an object. Point pnt4(3,4); is not allowed in CTS.

40 Summary: Value and Reference Types in CTS
In CTS, Value Types are Stack Objects: memory allocated at compile time on the stack auto destruction, no garbage collection needed less overhead, code runs faster less flexible, sizes need to be known at compile time In CTS, Reference Types are Heap Objects: memory allocated at run time on the heap garbage collected more flexible, sizes need not to be known at compile time more overhead, code runs slower Class defines reference types (heap objects) Struct defines value types (stack objects), even though “new” is used to create struct objects. Value types can’t derive from other types except interfaces.

41 Class Code class Point { public int x; public int y; }
Point p1 = new Point (); p1.x = 1; p1.y = 2; Point p2 = p1; // Copies the underlying pointer p2.x = 3; p2.y = 4; Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); Point p3; p3.x = 5; p3.y = 6;

42 Class Code class Point { public int x; public int y; }
Point p1 = new Point (); p1.x = 1; p1.y = 2; Point p2 = p1; // Copies the underlying pointer p2.x = 3; p2.y = 4; Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); // Writes "(3, 4)" Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); Point p3;//Creats a reference(pointer), no memory allocated p3.x = 5; // Will not compile p3.y = 6; // Will not compile

43 Struct Code struct Point { public int x; public int y; }
Point p1 = new Point(); //Creates a value object on stack. p1.x = 1; p1.y = 2; Point p2 = p1;//Makes a new copy of the object on the stack p2.x = 3; p2.y = 4; Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); // Writes "(1, 2)" Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); // Writes "(3, 4)" Point p3; //Creates a value object on the stack p3.x = 5; // It works. p3.y = 6; Console.WriteLine ("p3 = ({0}, {1})", p3.x, p3.y); // Writes "(5, 6)"

44 Arrays in C++ 5 10 0x 5 10 int a[2]; a[0] = 5; a[1] = 10;
// stack objects , size has to be known at compile time and can’t be changed at runtime. int size = 2; int *p; // a pointer p = new int[size]; p[0] = 5; p[1] = 10; // heap objects; dynamically allocated at runtime, “size” can be a variable delete p; // free the memory. a 5 10 p 0x 5 10

45 Arrays in CTS Array (same syntax for both class and struct):
Point[] pa = new Point[2]; pa[0] = new Point(); pa[1] = new Point(); Console.WriteLine ("pa[0] = ({0}, {1})", pa[0].x, pa[0].y); Console.WriteLine ("pa[1] = ({0}, {1})", pa[1].x, pa[1].y); Challenges: (1) Draw pictures to show the memory layout of pa for Point as a class and a struct. (2) What will happen when lines 2 and 3 are removed. Explain what will happen for Point as a class and then as a struct.

46 Boxing and Unboxing Boxing creates a copy of a value type on the managed heap (converts from value type to reference type) Unboxing duplicates a reference type on the stack (converts from reference type to value type) int val = 1;      // Declare an instance of a value type object  Object obj = val;  // Box it, inexplicit cast, an object containing value “1” is created on the heap and pointed to by reference “obj”. int val3 = (int) obj; // This will work, explicit cast. int val2 = obj;        // This won't compile. Why ?

47 Boxing & Unboxing Typecast: converting data from one type to another type. Widening: copying from a memory space of smaller value range to a memory space of larger value range. Narrowing: copying from a memory space of larger value range to a memory space of smaller value range. Boxing is widening and can be implicitly casted. Unboxing is narrowing and has to be explicitly casted. Monday Evening

48 Typecast References class Parent { int i; setParent(int k) {i=k;} }
class Child: Parent{ int j; public setChild(int m, int n) {i=m; j=n;} } Parent p1 = new Parent (); p1.setParent(1); Child c1 = new Child(); c1.setChild(2,3); // child objects can be treated as parent objects Parent p2 = (Parent) c1; p2.setParent(4); // don’t do this!!! parent objects can’t be treated as child objects Child c2 = (Child) p1; c2.setChild(5,6); Eve 2/23/16 will start here next.

49 Typecast References class Parent { int i; Parent(int k) {i=k;) }
You can typecast a child reference to parent reference, but never typecast a parent reference to a child reference. When we typecast the references, we do not alter the underlying objects (memory for the data.) Class type determines the memory layout. A child class inherits from its parent class, but not the other way around. A parent class does NOT inherit anything from its child classes. An object is an instance of a class, a real memory has the layout specified by the class. An object of a child type is an object of the parent type, but not the other way around. An object of a parent type is NOT an object of the child type. Day finished here. To Chapter 5. class Parent { int i; Parent(int k) {i=k;) } class Child: Parent{ int j; public set(int m, int n) {i=m; j=n;} Parent p1 = new Parent (1); Child c1 = new Child(); C1.set(2,3); Unboxing is narrowing and has to be explicitly casted.

50 More on C# Part III Enum, Generics, Event, Delegate, Versioning, NDD
Both day & Eve stop here at the end of week 4.

51 C# and CLR Generics Generics : parameterized types
According to Microsoft ( Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace. You can create your own generic interfaces, classes, methods, events and delegates. Generic classes may be constrained to enable access to methods on particular data types. Information on the types used in a generic data type may be obtained at run-time by means of reflection.

52 Event Mapping & Dispatching
Events A menu in C++: char c; bool done = false; while(!done) { cout << “Please make your selection, q to end:” cin >> c; switch(c) { case “+”: add( ); break; case “-”: sub( ); case “q”: done = true; } Event Loop Event Event Mapping & Dispatching Event Handler Monday, Day

53 Events & Delegates • .NET supports the development of GUI (Graphical User Interface) based EDPs (event-driven programs). Event loop and event mapping for such applications can be very complicate. .NET internally implemented the event loop and event mapping mechanism for such applications. The development of GUI-based applications in .NET needs only to design the GUI and write event handlers.

54 Events & Delegates • How can we register event handlers written by us to the event loop written by Microsoft? • The system event loop was implemented before the application event handlers and the names of the handlers are not pre-specified. • Event handlers are also called “callback methods”. Events are also called messages. • .NET implement this by using event & delegate constructs.

55 Events & Delegates • A delegate is a type-safe wrapper around a callback method. • Callback methods are used to respond to events. Three steps to understand events & delegates using an example Define a callback method to use a predefined Timer class Exam the Timer class which uses event & delegate Analyze the internal code of delegate

56 Usage of a Predefined Timer Class
// Call this callback method every 6 seconds. void UpdateData (Object sender, ElapsedEventArgs e) { // Update Data every 6 seconds. } // A Timer class has been implemented for us to use. // It has an event: Elapsed. Timer timer = new Timer (6000); timer.Elapsed += new ElapsedEventHandler (UpdateData); We registered a function pointer, UpdateData, as a callback, created a new instance of ElapsedEventHandler (a delegate) that wraps around (delegates to) UpdateData (a callback method) to respond to the Elapsed event.

57 Defining Events & Delegates
Inside the Timer class: public delegate void ElapsedEventHandler (Object sender, ElapsedEventArgs e); // specifies arguments for the callback public class Timer { public event ElapsedEventHandler Elapsed; … } // Calling the callback methods when the event occurs if (Elapsed != null) // Make sure somebody's listening, use Elapsed as a reference. Elapsed (this, new ElapsedEventArgs (...)); // Fire! Use Elapsed as a method, its arguments are sent to the callback methods.

58 Events & Delegates cont.
• A delegate is defined by placing the key word, delegate, in front of a global method. • The arguments of the method in the declaration are those of the callback functions. • The “real” argument of a delegate is always a pointer (to the callback function). • In the declaration of an event object, the type specifier between the “event” key word and the object name specifies the delegate to be used by the event to invoke event handlers. • An event object can be used as a reference and a method. • When an event object is used as a method, its arguments are sent to the callback methods, which are specified by the related delegate.

59 What’s Inside Events & Delegates?
public delegate void ElapsedEventHandler (Object sender, ElapsedEventArgs e); Compiles to: public class ElapsedEventHandler : MulticastDelegate // System.MulticastDelegate { public ElapsedEventHandler (object target, int method) { ... } public virtual void Invoke(object sender,ElapsedEventArgs e) { ... } ... } Use an event’s instance name as a method, actually call the Invoke method. It is a better way (a type safe way) to implement function pointers. (

60 The Fundamentals of C# What is it? How to define and use it?
Can you write a program? Can you trace a program? Do you know what’s going on inside?


Download ppt "C# for Unity3D Yingcai Xiao."

Similar presentations


Ads by Google