[初学Unity]Intermediate gameplay scripting

Properties

video

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

one more thing:
Fields

A *field *is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.

Static

Static Classes and Static Class Members (C# Programming Guide)

Method Overloading

待参考

Generics

Inheritance

Polymorphism

Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:

  • At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.
  • Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.

Method Hiding

When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version. Although you can hide members without using the new modifier, you get a compiler warning. If you use new to explicitly hide a member, it suppresses this warning.

Overriding

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

The override modifier extends the base class method, and the new modifier hides it.

You want objects that have values that are created from the derived class to use the methods that are defined in the derived class. You achieve that behavior by using override to extend the base class method.

一个很棒的例子,

using System;
using System.Text;

namespace OverrideAndNew
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass bc = new BaseClass();
            DerivedClass dc = new DerivedClass();
            BaseClass bcdc = new DerivedClass();

            // The following two calls do what you would expect. They call
            // the methods that are defined in BaseClass.
            bc.Method1();
            bc.Method2();
            // Output:
            // Base - Method1
            // Base - Method2


            // The following two calls do what you would expect. They call
            // the methods that are defined in DerivedClass.
            dc.Method1();
            dc.Method2();
            // Output:
            // Derived - Method1
            // Derived - Method2


            // The following two calls produce different results, depending 
            // on whether override (Method1) or new (Method2) is used.
            bcdc.Method1();
            bcdc.Method2();
            // Output:
            // Derived - Method1
            // Base - Method2
        }
    }

    class BaseClass
    {
        public virtual void Method1()
        {
            Console.WriteLine("Base - Method1");
        }

        public virtual void Method2()
        {
            Console.WriteLine("Base - Method2");
        }
    }

    class DerivedClass : BaseClass
    {
        public override void Method1()
        {
            Console.WriteLine("Derived - Method1");
        }

        public new void Method2()
        {
            Console.WriteLine("Derived - Method2");
        }
    }
}

Interface

An interface contains definitions for a group of related functionalities that a class or a struct can implement.
By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from another struct or class.

Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

keyword: this

How to: Implement and Call a Custom Extension Method (C# Programming Guide)中的一个例子:

The following example implements an extension method named WordCount in the CustomExtensions.StringExtension class. The method operates on the String class, which is specified as the first method parameter. The CustomExtensions namespace is imported into the application namespace, and the method is called inside the Main method.

using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
    //Extension methods must be defined in a static class
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
namespace Extension_Methods_Simple
{
    //Import the extension method namespace.
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            //  Call the method as if it were an 
            //  instance method on the type. Note that the first
            //  parameter is not specified by the calling code.
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}

Namespaces

The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types.

Lists and Directionaries

List Class

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Dictionary<TKey, TValue> Class

Represents a collection of keys and values.

Coroutines

Normal coroutine updates are run after the Update function returns. A coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes.

A coroutine is like a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame.
unity协程是一个能暂停执行,暂停后立即返回,直到中断指令完成后继续执行的函数。

By default, a coroutine is resumed on the frame after it yields but it is also possible to introduce a time delay using WaitForSeconds.

Different uses of Coroutines:

  • yield The coroutine will continue after all Update functions have been called on the next frame.
  • yield WaitForSeconds Continue after a specified time delay, after all Update functions have been called for the frame
  • yield WaitForFixedUpdate Continue after all FixedUpdate has been called on all scripts
  • yield WWW Continue after a WWW download has completed.
  • yield StartCoroutine Chains the coroutine, and will wait for the MyFunc coroutine to complete first.

http://unity3d.com/learn/tutorials/topics/scripting/coroutines?playlist=17117
视频中的第二个例子没能完成,缺少一个Script。
并没有,看看我的第一帖

参考链接:

Quaternions

Quaternions are used to represent rotations and are the best way to deal with rotations.
They are compact, don't suffer from gimbal lock and can easily be interpolated. Unity internally uses Quaternions to represent all rotations.

  • Quaternion.LookRotation(Vector3 forward, Vector3 up = Vector3.up);
    Creates a rotation with the specified forward and upwards directions.

  • Quaternion.Slerp(Quaternion a, Quaternion b, float t);
    Spherically interpolates between a and b by t. The parameter t is clamped to the range [0, 1].

  • Quaternion.identity
    This quaternion corresponds to "no rotation" - the object is perfectly aligned with the world or parent axes.

Delegates

A delegate can be thought of simply as a container for a function.
It can be passed around or used like a variable.

// Declare delegate -- defines required signature:
delegate double MathAction(double num);

class DelegateTest
{
    // Regular method that matches signature:
    static double Double(double input)
    {
        return input * 2;
    }

    static void Main()
    {
        // Instantiate delegate with named method:
        MathAction ma = Double;

        // Invoke delegate ma:
        double multByTwo = ma(4.5);
        Console.WriteLine("multByTwo: {0}", multByTwo);

        // Instantiate delegate with anonymous method:
        MathAction ma2 = delegate (double input)
        {
            return input * input;
        };

        double square = ma2(5);
        Console.WriteLine("square: {0}", square);

        // Instantiate delegate with lambda expression
        MathAction ma3 = s => s * s * s;
        double cube = ma3(4.375);

        Console.WriteLine("cube: {0}", cube);
    }
    // Output:
    // multByTwo: 9
    // square: 25
    // cube: 83.740234375
}

Attributes

ExecuteInEditMode
Makes a script execute in edit mode.
By default, script components are only executed in play mode. By adding this attribute, each script component will also have its callback functions executed while the Editor is not in playmode.

RangeAttribute
Attribute used to make a float or int variable in a script be restricted to a specific range.
When this attribute is used, the float or int will be shown as a slider in the Inspector instead of the default number field.

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.

原文地址:https://www.cnblogs.com/ice-mj/p/5734740.html