Unity (12) MVC framework: A simulated application of MVC programming patterns

Source: Internet
Author: User

MVC is a pattern of creating WEB applications using MVC (Model View Controller-View-controller) Design:
    • Model (models) represent the core of the application (such as a list of database records).
    • View displays data (database records).
    • The controller (Director) processes the input (writes to the database record).

: Simulation Press button to increase experience, experience changes, the player reached the current level *100 experience after the upgrade, upgrade to the player to increase the current level *10 gold coins, every 3 levels to increase the diamond 10;

1. Create an avatar panel to simulate the MVC pattern

2. Create a SQL database to save player data

2. Add 4 scripts to head:

Model: Playermodel Script code:

usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine;/// <summary>///delegate with value change/// </summary>/// <param name= "value" ></param> Public Delegate voidOnvaluechangeeventhandle (floatvalue); Public classplayermodel:monobehaviour{Private floatplayerexperience; Private intPlayerLevel; Private intPlayercoin; Private intPlayerdiamond; /// <summary>    ///Experience Change event (cat came in = Experience changed),///The escape method of observing the cat's animal is triggered (a method triggered by registering an object that has experienced changing the event))///UI Updates Display method triggers, method triggers for database updates/// </summary>     Public EventOnvaluechangeeventhandle Onexperiencechange; /// <summary>    ///Player Experience/// </summary>     Public floatPlayerexperience {Set{playerexperience=value; //experience is updated (experience is changed), triggering events, calling all methods that bind to the eventOnexperiencechange (playerexperience); }        Get        {            returnplayerexperience; }    }    /// <summary>    ///player Level/// </summary>     Public intPlayerLevel {Set{playerlevel=value; //trigger experience Change events after experience updateOnexperiencechange (playerexperience); }        Get        {            returnPlayerLevel; }    }    /// <summary>    ///Player Gold/// </summary>     Public intPlayercoin {Set{Playercoin=value; //trigger event after experience updateOnexperiencechange (playerexperience); }        Get        {            returnPlayercoin; }    }    /// <summary>    ///player Diamond/// </summary>     Public intPlayerdiamond {Set{Playerdiamond=value; //Triggering EventsOnexperiencechange (playerexperience); }        Get        {            returnPlayerdiamond; }    }}

View: Playerview

usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine;usingUnityengine.ui; Public classPlayerview:monobehaviour { PublicText Leveltext;  PublicText Experiencetext;  PublicSlider Experienceslider;  PublicText Cointext;  PublicText Diamondtext; PrivatePlayermodel model;  PublicButton addexpbut; Private voidAwake () {model= getcomponent<playermodel>(); }    /// <summary>    ///Display data (registered in the event, when the event is triggered, the method is called)/// </summary>    /// <param name= "ex" ></param>     Public voidShowData (floatex) {Leveltext.text=model.        Playerlevel.tostring (); Experiencetext.text= Model. Playerexperience.tostring () +"/"+ (model. playerlevel* -).        ToString (); Cointext.text=model.        Playercoin.tostring (); Diamondtext.text=model.        Playerdiamond.tostring (); Experienceslider.value= Model. Playerexperience/(model. PlayerLevel * -); }}

Controller: Playercontroller Code:

usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine; Public classPlayercontroller:monobehaviour {PrivatePlayermodel model; PrivatePlayerdb DB; PrivatePlayerview View; Private voidAwake () {model= getcomponent<playermodel>(); DB= getcomponent<playerdb>(); View= getcomponent<playerview>(); }    voidStart () {//Open DatabaseDb. OPENDB ("MVC"); //The way the data is displayed in the UI, bound to the experience Change eventModel. Onexperiencechange + =view.        ShowData; //synchronizing data from a database to a modeldb.             Synchronization (); //methods of database operations, binding to experience changing eventsModel. Onexperiencechange + =db.        Updateplayerdata; //add experience to the method that binds to the mouse click eventView.addExpBut.onClick.AddListener (Onbtnclick); }    Private voidOnDestroy () {db. Closedb (); //Close the database    }    voidOnbtnclick () {addexperience ( -);//Increased Experience    }    /// <summary>    ///Increased Experience/// </summary>    /// <param name= "exp" ></param>     Public voidAddexperience (floatexp) {        //Current experience = already experienced + increased experience        floatCurrentexp = model. Playerexperience +exp;  while(Currentexp>model. playerlevel* -)        {            //Get remaining experienceCURRENTEXP-= model. PlayerLevel * -; //UpgradeModel. playerlevel++; //Gold IncreaseModel. Playercoin + = model. PlayerLevel *Ten; //3 diamonds per litre added            if(model. playerlevel%3==0) {model. Playerdiamond+=Ten; }              }        //residual experience assignment to modelModel. Playerexperience =Currentexp; }}

Database operations: PLAYERDB code:

Using System.Collections;
Using System.Collections.Generic;
Using Unityengine;
Using Mono.Data.Sqlite;
public class Playerdb:monobehaviour
{
private string DataPath;
Private Sqlitecommand command;
Private Sqliteconnection con;
Private Sqlitedatareader reader;
Private Playermodel Playermodel;
private void Awake ()
{
Playermodel = getcomponent<playermodel> ();
}
<summary>
Open Database
</summary>
<param name= "DBName" ></param>
public void Opendb (string DBName)
{
Patchwork paths
DataPath = "Data source==" + Application.streamingassetspath +
"/" + DBName + ". SQLite";
con = new Sqliteconnection (DataPath);
Command = con. CreateCommand ();
Con. Open ();

}

<summary>
Close the database
</summary>
public void Closedb ()
{
Reader. Close ();
reader = null;
Con. Clone ();
}

<summary>
Update the Player database (already registered in the experience Change event, this method will be called when the experience has changed)
</summary>
<param name= "Ex" ></param>
public void Updateplayerdata (float ex)
{
string query = "Update playerdata Set playerlevlel= '" +
Playermodel.playerlevel + "', playerexperience= '" +
Playermodel.playerexperience + "', playercoin= '" +
Playermodel.playercoin + "', playerdiamond= '" + Playermodel.playerdiamond + "'";
Command.commandtext = query;
Command. ExecuteNonQuery ();
}

<summary>
Synchronizing database data to a model
</summary>
public void Synchronization ()
{

string query = "SELECT * from Playerdata";
Command.commandtext = query;
Reader = command. ExecuteReader ();
Reader. Read ();
Synchronize to model
playermodel.playerlevel = Int. Parse (reader. GetValue (0). ToString ());
Playermodel.playercoin = System.Convert.ToInt32 (reader. GetValue (2). ToString ());
Playermodel.playerdiamond = Int. Parse (reader. GetValue (3). ToString ());
Playermodel.playerexperience = float. Parse (reader. GetValue (1). ToString ());
Reader. Close ();
}
}

Unity (12) MVC framework: A simulated application of MVC programming patterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.