This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

  • πŸ“’ welcome to like πŸ‘ collect ⭐ message πŸ“ if there is an error please correct!
  • πŸ“’ This article was originally written by dumb code Y at πŸ™‰
  • πŸ“’ The future is long and worth striving for a better life ✨

πŸ“’ preface

For a long time did not do some small cases to play, today a whim to do a roll call artifact to play!

In fact, this function is very simple to make, but is in a list of a random value displayed on the surface!

Let’s take a look at how this small case is made!


πŸ“Unity to do a computer and mobile phone can be used directly [roll call artifact], can be imported into Excel documents directly used

Everyone should be Unity can be packaged into a computer directly run exe file, can also be packaged into a mobile phone directly run APP file

So I thought about making a magic roll call device with a little more function

That is to add an optional Excel document. We can add all the names to the Excel document in advance

I will do it step by step to show you! The Unity version used by the blogger is: 2020.3.8f1c1


πŸ‹ First step, open Unity and create a new project

Open theUnityHubNew versions of Unity need to use UnityHub to run a new projectSet theThe project nameandThe pathAnd then clickcreateCan!

Then wait for the newly created Unity to load


🍊 Step 2, how to read the data in Excel document and use it

  • The idea of doing this is very simple, is from a name library surface randomly read a name display to the UI can!

  • You can create a List, enter all the names in the List, and then read it

  • We can put the List of students into Json or Excel access, and then directly input the List in the script can be used

  • But I think Excel may be more convenient to use in the actual situation, after all, people who use computers can use Excel, but not necessarily use Json and so on!

  • This is a great example of how to read Excel files.

First of all, want to read the Excel file in unity to guide library files Excel. DLL and ICSharpCode SharpZipLib library file official link: exceldatareader.codeplex.com/

Example Excel file:

After importing the library files Excel. DLL and icsharpcode. SharpZipLib, create a script for StudentDemo in Unity

Example code is as follows:

using System.IO;
using Excel;
using System.Data;
using UnityEngine;

public class StudentDemo : MonoBehaviour
{
    void Start()
    {
        FindXLSX();
    }
    
    void FindXLSX()
    {
        FileStream stream = File.Open(Application.dataPath, FileMode.Open, FileAccess.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

        DataSet result = excelReader.AsDataSet();

        int columns = result.Tables[0].Columns.Count;
        int rows = result.Tables[0].Rows.Count;

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                string nvalue = result.Tables[0].Rows[i][j].ToString(); Debug.Log(nvalue); }}}}Copy the code

This script reads Excel files in the specified File path through file. Open

Then, through the method in the library file, the data in Excel is saved into a string format that Unity can use, and then the data can be retrieved and used through traversal

For example, the result of the above script execution is:Then you can create a list to call the list.


πŸ‡ Step 3, import the student List into the List and display a random name

  • In the previous step we passedReading Excel filesGot data on the names of the students
  • That next is to use this list reasonably, to achieve an effect we want!

Let’s set up a simple UI in the scene that will be used to display the roll call function later

Start by adding two buttons to the scene and three Text Text buttons to randomize the list and start the roll call, and Text Text to display the title, list, and roll call

Then put theRender mode for the cameraSet to solid color mode and simply select a color

The simple effect is as followsThen you need to continue adding code to the script. The complete code is as follows:

using System.IO;
using Excel;
using System.Data;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

public class StudentDemo : MonoBehaviour
{
    public Button FindXLSXBtn;
    public Button startNameBtn;

    public Text NameText;
    public Text NameSum;

    private List<string> StudentNameList;
    private int aName;
    private bool ISrandom = true;
    private bool IsOK = true;

    private void Start()
    {
        StudentNameList = new List<string> (); FindXLSXBtn.onClick.AddListener(FindXLSX); startNameBtn.onClick.AddListener(startName); StudentNameList.Add("One more time!);
    }
    private void Update()
    {
        if(! ISrandom) { NameText.text = StudentNameList[Random.Range(0, StudentNameList.Count)]; }}void FindXLSX()
    {
        ISrandom = false;

        if (IsOK)
        {
            IsOK = false;
            FileStream stream = File.Open(Application.dataPath + "/StudentName.xlsx", FileMode.Open, FileAccess.Read);
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            DataSet result = excelReader.AsDataSet();

            int columns = result.Tables[0].Columns.Count;
            int rows = result.Tables[0].Rows.Count;

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    string nvalue = result.Tables[0].Rows[i][j].ToString();
                    StudentNameList.Add(nvalue);
                    // Debug.Log(nvalue);
                    NameSum.text += nvalue + "\n"; }}}}/// <summary>
    ///Roll call start
    /// </summary>
    void startName(){ ISrandom = ! ISrandom; aName = Random.Range(0, StudentNameList.Count); NameText.text = StudentNameList[aName]; }}Copy the code

Code parsing:

Add Button click events to the code, create a List to store lists read from Excel files, and add lists to the List during traversal

Range method to generate a Random number with a minimum value of 0 and a maximum value of the List’s maximum index

The list is then displayed randomly in the Update via random.range

Then write a roll call method, randomly read a list of values displayed in our roll call list

Two bool values ISrandom and IsOK are used to control the random display of the list and Update

The actual effect after the script is mounted is as follows:Okay, so now we just need to get itExcel fileCan normally read the list of students and random read!

But now there is a problem, our Excel file path is written dead, the Excel file read now is my implementation in the project put!

In this case, I can only use my own student list in Excel, which is not useful ~

The next step is to add a method that reads Excel itself. Read on!


🍈 Step 4, open the folder and select the Excel file

We have now implemented the method of reading Excel files and randomly displaying the names, but we need one more step

That’s how to get Unity to open folders and select Excel files!

I didn’t find an official API for this function to call directly, so I used another open folder scheme instead

Create a new script, OpenFileName, with the following code:

using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

public class OpenFileName
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
}

public class WindowDll{[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
    public static bool GetOpenFileName1([In, Out] OpenFileName ofn)
    {
        returnGetOpenFileName(ofn); }}Copy the code

Just know that this script is used to call the system interface.

Then go ahead and add a new method to our StudentDemo script:

 public void OpenFileWin()
    {
        ofn.structSize = Marshal.SizeOf(ofn);

        ofn.filter = "All Files\0*.*\0\0";

        ofn.file = new string(new char[256]);

        ofn.maxFile = ofn.file.Length;

        ofn.fileTitle = new string(new char[64]);

        ofn.maxFileTitle = ofn.fileTitle.Length;
        string path = Application.dataPath;
        path = path.Replace('/'.'\ \');
        // The default path
        ofn.initialDir = path;
        //ofn.initialDir = "D:\\MyProject\\UnityOpenCV\\Assets";  
        ofn.title = "Open Project";

        ofn.defExt = "xlsx";// Display the type of file
        // Note that the items need not be all selected but the item 0x00000008 is not missing
        ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR  

        if (WindowDll.GetOpenFileName(ofn))
        {
            Debug.Log("Selected file with full path: {0}"+ ofn.file); }}Copy the code

This method is used to start the system window, on the Button click event directly call this method can call open folder function!

Then we add a Button to the script and click the event to execute the method we just added above.

The complete code for the script is as follows:

using System.IO;
using Excel;
using System.Data;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public class StudentDemo : MonoBehaviour
{
    public Button OpenFileWinBtn;
    public Button FindXLSXBtn;
    public Button startNameBtn;

    public Text NameText;
    public Text NameSum;

    private List<string> StudentNameList;
    private int aName;
    private bool ISrandom = true;
    private bool IsOK = true;
    private OpenFileName ofn;

    private void Start()
    {
        ofn = new OpenFileName();
        StudentNameList = new List<string> (); OpenFileWinBtn.onClick.AddListener(OpenFileWin); FindXLSXBtn.onClick.AddListener(FindXLSX); startNameBtn.onClick.AddListener(startName); StudentNameList.Add("One more time!);
    }
    private void Update()
    {
        if(! ISrandom) { NameText.text = StudentNameList[Random.Range(0, StudentNameList.Count)]; }}void FindXLSX()
    {
        ISrandom = false;

        if (IsOK)
        {
            IsOK = false;
            FileStream stream = File.Open(ofn.file, FileMode.Open, FileAccess.Read);
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            DataSet result = excelReader.AsDataSet();

            int columns = result.Tables[0].Columns.Count;
            int rows = result.Tables[0].Rows.Count;

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    string nvalue = result.Tables[0].Rows[i][j].ToString();
                    StudentNameList.Add(nvalue);
                    // Debug.Log(nvalue);
                    NameSum.text += nvalue + "\n"; }}}}/// <summary>
    ///Roll call start
    /// </summary>
    void startName(){ ISrandom = ! ISrandom; aName = Random.Range(0, StudentNameList.Count);
        NameText.text = StudentNameList[aName];
    }

    public void OpenFileWin()
    {
        ofn.structSize = Marshal.SizeOf(ofn);

        ofn.filter = "All Files\0*.*\0\0";

        ofn.file = new string(new char[256]);

        ofn.maxFile = ofn.file.Length;

        ofn.fileTitle = new string(new char[64]);

        ofn.maxFileTitle = ofn.fileTitle.Length;
        string path = Application.dataPath;
        path = path.Replace('/'.'\ \');
        // The default path
        ofn.initialDir = path;
        //ofn.initialDir = "D:\\MyProject\\UnityOpenCV\\Assets";  
        ofn.title = "Open Project";

        ofn.defExt = "xlsx";// Display the type of file
        // Note that the items need not be all selected but the item 0x00000008 is not missing
        ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR  

        if (WindowDll.GetOpenFileName(ofn))
        {
            Debug.Log("Selected file with full path: {0}"+ ofn.file); }}}Copy the code

This example uses only two scripts, one is OpenFileName, the other is StudentDemo, directly mount to the scene.

The effect is shown as follows:


πŸ‰ Last step, package as an EXE file available on the PC side

A basic roll call case we are almost done, there is still one last step, packaged into a direct use of the EXE file

This step is very simple and can be done.

Click the menu key: File -> Build Setting, then add the scene to the Build, click Player Setting, and change Produce Name and Company Name in the panel

Old Versions of Unity also need to go to the properties pane below to change PakecageName.

Finally clickBuild, and then select a folder to save it!The package is as follows:And then we click on thisExe fileCan run, run as follows:

Tip: I found that the Excel file could not be read after the packaging was completed, which was a serious problem. As a result, our list library could not be used normally, so we could not randomly select a list. I checked on the Internet and found that the packaged EXE file cannot call the Excel DLL file, so I imported other DLL files to make the packaged EXE file can also be used normally! The source code project below all have, may own experience!


🎁 Resources download

All the Excel related DLLS, case source and packaged exe files mentioned in this article are in this resource

Need small partners can download their own experience oh! Especially teachers who need to use roll call

You can open the EXE file and upload the student list of Excel file can be directly named oh!!

Click resources to download


πŸ’¬ summary

  • This article USES theUnityHow to make a detailed introduction[Roll call artifact]Tutorials can also be importedExcel fileDirect use oh!
  • I accidentally wrote 10,000 words from oneNew perspectiveI wrote this tutorial
  • Like small partners can download resources to experience oh!
  • Due to the limited time, I have not built a good-looking UI, but I will produce one when I have timeVersion 2.0, the function is more perfect and better look oh!
  • Click on the article if you find it usefulThree evenOh! Watch me take you to learn moreThe Unity of knowledge!