programing

Unity - 클라이언트 측 Javascript 및 Ajax와 통신합니다.통합에서 웹 페이지로 데이터를 반환하려면 어떻게 해야 합니까?

newnotes 2023. 3. 21. 22:33
반응형

Unity - 클라이언트 측 Javascript 및 Ajax와 통신합니다.통합에서 웹 페이지로 데이터를 반환하려면 어떻게 해야 합니까?

제가 정말 묻고 싶은 것은 이것입니다.유니티 빌드로 컴파일할 수 없는 의존관계가 있는 경우에도 유니티 내에서 호출하여 웹 사이트에서 브라우저로 로드된 스크립트를 사용하여 그들과 통신할 수 있는 방법이 있습니까?

관련 매뉴얼에서는 이 문제에 대해 자세히 설명하지 않습니다.https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html

유니티 어플리케이션용 웹사이트 래퍼를 만들고 있습니다.체험용 버튼은 웹사이트 내에 있습니다.버튼은 유니티 어플리케이션뿐만 아니라 사이트의 나머지 부분에도 영향을 미칩니다.

단, 유니티 게임 플레이에 특정 콘텐츠가 로드되면 앱이 웹사이트에 영향을 미칠 수 있어야 합니다.데이터를 창의적인 방법으로 웹 사이트에 전달할 수 있는 방법이 있습니까?현재 웹사이트의 Javascript 코드를 모두 유니티 컴파일에 포함시키고 있으며, 다음과 같은 오류가 발생하고 있습니다.

gameInstance = UnityLoader.instantiate("gameContainer", "/Build/DomumProto16_Web.json", {
    onProgress: UnityProgress
}); 

웹 사이트에서 게임 플레이로 데이터 전송:

gameInstance.SendMessage('Manager','Filter', JSON.stringify(filterActive));

유니티 게임 플레이에서 이 함수를 호출해야 합니다.단, ajax.ajax_url은 백엔드의 wp_localize_script()를 사용하여 현지화되므로 정의되지 않습니다.

function showStudentWork(studentIndex){
        
    //make sure to remove all the 
    var x = document.getElementById("studentWork");

    var studentID = studentWork[studentIndex];
    console.log(studentID);
    
    $.ajax({
        url: ajax.ajax_url,
        type: "POST",
        data: {
            action: 'getStudentPost',
            currentStudent: studentID
        },
        success: function (data) {
            x.innerHTML = "";
            x.innerHTML = data;
            x.style.display = "grid";
        },
        error: function (error) {
            console.log(`Error ${error}`);
        }
    });
    
    return false;

}

제가 정말 묻고 싶은 것은 이것입니다.유니티 빌드로 컴파일할 수 없는 의존관계가 있는 경우에도 유니티 내에서 호출하여 웹 사이트에서 브라우저로 로드된 스크립트를 사용하여 그들과 통신할 수 있는 방법이 있습니까?

여기 두 가지 방법이 있습니다.하나는, 내 생각에, 더 쉽지만, 그것은 더 이상 사용되지 않으므로, 당신은 그것을 사용해서는 안 된다.두 번째 옵션은 '올바른' 방식이지만, 좀 추한 IMO입니다.

옵션 1: 어플리케이션.외부 콜

문서

이 옵션을 사용하면 브라우저 javascript에 직접 문의할 수 있지만, Unity는 이를 지원하지 않기 때문에 장기적으로는 좋지 않을 수 있습니다.

Unity Web Player가 동작하고 있는 브라우저에서는 다음 사항을 고려해 주십시오.브라우저 소스에서 javascript 함수를 정의합니다.

<other html>
<script>
function foo(msg) {
    alert(msg);
}
</script>

유니티에서는, 항상 nesecary가 됩니다.

Application.ExternalCall( "foo", "The game says hello!" );

이를 통해 Javascript를 Unity에서 호출할 수 있습니다.반대 방향의 통신에도 비슷한 기능이 있습니다.

옵션 2: jslibs

문서

이것이 통일성이 결여된 작업 방식입니다.javascript 라이브러리를 게임에 패키징하는 것을 포함했습니다.

먼저 게임과 함께 패키징되는 Javascript 파일을 만듭니다.다음은 샘플 파일입니다.

// Unity syntactic sugar
mergeInto(LibraryManager.library, {
    // Declare all your functions that can be called from c# here
    alert_user: function (msg) {
        window.alert(msg);
    },
    other_func: function () {
     // does something else
     // etc.
     // put as many functions as you'd like in here
    }
}

파일에는 확장자를 ..jslib 안에서Plugins폴더를 선택합니다.

그런 다음 c# 파일에서 다음을 수행해야 합니다.

// Declare a monobehavior, whatever
using UnityEngine;
using System.Runtime.InteropServices;

public class NewBehaviourScript : MonoBehaviour {

    // IMPORTANT
    // You have to declare the javascript functions you'll be calling
    // as private external function in your c# file. Additionally,
    // They need a special function decorator [DllImport("__Internal")]
    // Example:
    [DllImport("__Internal")]
    private static extern void alert_user(string msg);

    // With that unpleasantness over with, you can now call the function
    void Start() {
        alert_user("Hello, I am a bad person and I deserve to write c#");
    }
}

에트 비올라c# javascript에서 다른 javascript를 호출하여 dom과 대화할 수 있지만 모든 결정은 당신에게 맡기겠습니다.

반대 방향

어느 경우든 반대 방향의 통신(브라우저가 Unity에 무언가를 말함)은 같은 형식입니다.

javascript를 .UnityInstance(이 방법은 이 답변에 넣기엔 좀 긴 말이지만, 어느 쪽인가의 문서를 체크해 주세요).그냥 ㅇㅇㅇㅇㅇ..sendMessage.

예: c#

...
void DoSomething (string msg) {
    // this is a c# function that does something in the game
    // use your imagination
}
...

javascript:

let game = UnityLoader // Actually load the game here
game.SendMessage('TheNameOfMyGameObject', 'DoSomething', 'This is my message');

다음 방법으로 할 수 있다고 이해하면WWW 함수

이것은 올바른 코드가 아닙니다.이건 그냥 너에게 좋은 생각이 될 거야.

PHP 함수로 변수 보내기

string url = "" // add your URL here;
WWWForm form = new WWWForm ();
form.AddField("YourFunctionName", "SampleFunction");
WWW www = new WWW(url, form);
yield return www;

이제 PHP에서 다음과 같은 작업을 수행합니다.

function YourFunctionName()
{
  // your function code here
}

그리고 이제

$YourFunctionName = $_POST["functionName"];
 switch ($functionName){
 case "SampleFunction":
    SampleFunction();
    break;
 }

그래서 이 아이디어는 여전히 PHP가 필요하고, 그 PHP에서 당신의 ajax를 호출해야 한다는 것입니다.

언급URL : https://stackoverflow.com/questions/64533232/unity-communicating-with-clientside-javascript-and-ajax-how-to-pass-data-back

반응형