c# - 使用 Unity C# 和 PHP 的动态争夺游戏(Mysql 作为数据库)

标签 c# php mysql unity3d

我这里有代码,可以根据 this 对声明的单词进行加扰video.Below 是依赖于我在 Unity Editor 上声明的单词数组的代码。问题是我希望它是动态的,就像它会将单词提取到数据库中一样。我在 php 中编写了一个代码,用于从 db 检索数据,并在 csharp 上编写了一个代码,该代码通过 WWW 方法读取 php。我无法合并这两个过程 - 打乱单词和从 db 获取单词,请帮助我,谢谢。

this是我的 Unity 拼词设置。如您所见,我将 WordScrambe.cs 附加到 Core Gameobject 并声明了 2 个词——“YES”和“YOURS”。

字符对象.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CharObject : MonoBehaviour {
public char character;
public Text text;
public Image image;
public RectTransform rectTransform;
public int index;

[Header("Appearance")]
public Color normalColor;
public Color selectedColor; 

bool isSelected= false;

public CharObject Init(char c)
{
    character = c;
    text.text = c.ToString ();
    gameObject.SetActive (true); 
    return this;
}

public void Select()
{
    isSelected = !isSelected;
    image.color = isSelected ? selectedColor : normalColor;
    if (isSelected) {
        WordScramble.main.Select (this);
    } else {
        WordScramble.main.UnSelect();
    }
}
}

WordScramble.cs

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    [System.Serializable]
    public class Word
    {
        public string word; 
        [Header("leave empty if you want randomized")]
        public string desiredRandom; 
    
        public string GetString() 
        {
            if (!string.IsNullOrEmpty (desiredRandom))
            {
                return desiredRandom;
            }
            string result = word;
    
    
            while (result==word) 
            {
                result = ""; 
                List<char> characters = new List<char> (word.ToCharArray ()); 
                while (characters.Count > 0) 
                {
                    int indexChar = Random.Range (0, characters.Count - 1); 
                    //Debug.Log(characters[indexChar]);
                    result += characters [indexChar]; 
                    Debug.Log(word);
                    characters.RemoveAt (indexChar);
                }
            }
    
            return result;
            
        }// end of Getstring Method
    }
    
    public class WordScramble : MonoBehaviour {
    
        public Word[] words;
    
        [Header("UI REFERENCE")]
        public CharObject prefab;
        public Transform container;
        public float space;
        public float lerpSpeed=5;
    
        List<CharObject> charobjects = new List<CharObject>();
        CharObject firstSelected;
    
        public int currentWord;
        public static WordScramble main;
    
        void Awake()
        {
            main = this;
        }
    
    
    
        // Use this for initialization
        void Start () {
            ShowScramble (currentWord);
        }
        
        // Update is called once per frame
        void Update ()
        {
            RepositionObject ();
        }
    
        void RepositionObject()
        {
            if (charobjects.Count==0) {
                return;
            }
            float center = (charobjects.Count -1) / 2;
            for (int i = 0; i < charobjects.Count; i++)
            {
                charobjects[i].rectTransform.anchoredPosition= Vector2.Lerp(charobjects[i].rectTransform.anchoredPosition, new Vector2((i- center)* space,  0), lerpSpeed* Time.deltaTime) ;
                charobjects [i].index = i;
            }
    
        }
        //show a random word to the screen
        public void ShowScramble()
        {
            ShowScramble (Random.Range (0, words.Length - 1)); 
        }
        //<summary>Show word from collection with desired index
        public void ShowScramble(int index)
        {
            charobjects.Clear ();
            foreach (Transform child in container) {
                Destroy (child.gameObject);
            }
            //Words Finished
            if (index > words.Length - 1) {
                Debug.LogError ("index out of range, please enter range betwen 0-" + (words.Length - 1).ToString ());
                return;
            }
    
            char[] chars = words [index].GetString ().ToCharArray ();
            foreach (char c in chars) 
            {
                CharObject clone = Instantiate (prefab.gameObject).GetComponent<CharObject> ();
                clone.transform.SetParent (container);
    
                charobjects.Add (clone.Init (c));
            }
    
            currentWord = index;
        }
        public void Swap(int indexA, int indexB)
        {
            CharObject tmpA = charobjects [indexA];
    
            charobjects[indexA] = charobjects [indexB];
            charobjects[indexB] = tmpA;
    
            charobjects [indexA].transform.SetAsLastSibling ();
            charobjects [indexB].transform.SetAsLastSibling ();
    
            CheckWord ();
        }
    
        public void Select(CharObject charObject)
        {
            if (firstSelected) 
            {
                Swap (firstSelected.index, charObject.index);
    
                //Unselect
    
                firstSelected.Select();
                charObject.Select();
    
            } else {
                firstSelected = charObject;
            }
        }
        public void UnSelect()
        {
            firstSelected = null;
        }
        public void CheckWord()
        {
            StartCoroutine (CoCheckWord());
        }
        IEnumerator CoCheckWord()
        {
            yield return new WaitForSeconds (0.5f);
            string word = "";
            foreach (CharObject charObject in charobjects)
            {
                word += charObject.character;
            }
            if (word == words [currentWord].word) {
                currentWord++;
                ShowScramble (currentWord);
    
    
            }
    
        }
    }
    

下面是使用 PHP 从数据库中检索数据并将数据传递给 unity 的代码。

读取.php

    <?php
    include '../../connection.php';
    
    $query=mysqli_query($conn, "SELECT * FROM words");
    while($fetch=mysqli_fetch_array($query)){
            
        echo $get=$fetch["words"];
        echo ",";
    }
    
    ?>

fetch.cs-我同时将其附加到 Unity Editor 上的 Main Camera。

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class fetch : MonoBehaviour {
    
        
        public string[] dbWords;
    
         IEnumerator Start(){
            WWW words=new WWW("http://localhost/bootstrap/android/v2/read.php");
            yield return words;
            string wordsDataString=words.text;
            print(wordsDataString);
            dbWords=wordsDataString.Split(',');
        }
    }

总之我想在unity中做一个scramble game,它的话依赖于数据库。我有单词争夺(但静态)和从数据库中检索数据但没有连接到我制作的争夺游戏的过程,这意味着我的项目还不是动态的,对于不清楚的解释我很抱歉。 谢谢你和更多的力量! :)

最佳答案

欢迎来到 SO!

目前还不完全清楚您的问题出在哪里,但我认为您的意思是说您没有从数据库中收到结果?

让我们首先将您的数据库逻辑移动到一个单独的类中,以获得良好的实践。 此外,MonoBehaviour 的 Start 方法的返回类型为 void,而不是 IENumerator。您需要一个 IENumerator,您可以使用 StartCoroutine 调用它。

像下面这样创建一个单独的类

public static class NetworkManager
{
    public static IEnumerator Fetch(Action<string[]> callback)
    {
        WWW words=new WWW("http://localhost/bootstrap/android/v2/read.php");
        yield return words;
        string wordsDataString=words.text;
        print(wordsDataString);
        var result = wordsDataString.Split(',');

        callback?.Invoke(result);
    }
}

我无法测试您的 Fetch 方法中的代码,因为您是在本地使用它,但我们假设它现在可以正常工作。

注意回调作为参数。 这允许您注册一个将在数据库调用完成后触发的操作。

它在方法的最后一行被调​​用。 然后您可以像这样调用该方法:

public class SomeClass : MonoBehaviour
{
    StartCoroutine(NetworkManager.Fetch( (words) => 
    {
        // Do something with the words!
        SomeMethod(words);
    });
}

一旦协程完成,括号内的任何代码都会被执行。在这种情况下,将触发接受单词作为参数的“SomeMethod”。

我希望这能澄清并回答您的问题!

关于c# - 使用 Unity C# 和 PHP 的动态争夺游戏(Mysql 作为数据库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52078352/

相关文章:

c# - 从 int 列获取值会导致 "no implicit conversion between ' int' 和 null"错误

javascript - 从表输入中获取总计作为 jquery 中的总计

php - 如何将绑定(bind)参数与值数组一起使用?

php - 尝试将双引号表单数据库打印到输入字段中

c# - 如何在 Windows 8 中安装 XNA Game Studio 4.0?

c# - 尝试从 wsdl 生成服务引用时出错

c# - ASP.NET/C# 中的服务器端麦克风捕获

php - 预订表格有效,但不提供反馈

javascript - 在下拉列表中显示来自另一个文件的数据(php、mysql、javascript)

mysql - SQL Server 相当于 MySQL Load xml infile