使用unity c#和php(mysql作为数据库)的动态拼图游戏

kb5ga3dv  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(318)

我这里有一些代码,可以根据这个视频对声明的单词进行置乱。下面是依赖于我在unity编辑器中声明的单词数组的代码。问题是我希望它是动态的,就像它将把单词带入数据库一样。我用php编写了一个从db检索数据的代码,用csharp编写了一个通过www方法读取php的代码。我不能合并这两个过程-加扰词和从数据库获取词,请帮助我的家伙,谢谢。
这是我的拼字游戏。正如你所见,我把wordscrambe.cs附加到核心游戏对象上,并声明了两个词——“是的”和“你的”。
字符对象.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从db检索数据并将数据传递给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-i同时把它连接到unity编辑器的主摄像头上。

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(',');
        }
    }

简言之,我想做一个拼凑游戏,在团结的话,它取决于数据库。我有字扰码(但静态)和检索数据库中的数据,但没有连接到扰码游戏我做的过程,这意味着我的项目还不是动态的,我很抱歉解释不清。谢谢你,还有更多的力量!:)

6ju8rftf

6ju8rftf1#

欢迎来到so!
现在还不完全清楚你的问题出在哪里,但是我认为你的意思是说你没有从你的数据库中得到一个结果?
让我们从将数据库逻辑移到一个单独的类开始,以获得良好的实践。同样,monobhavior的start方法是returntype 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”将触发。
我希望这能澄清和回答你的问题!

相关问题