Load object from Asset Bundle - unity3d

I have Download and Main cs files. The first one contains method LoadAsset
public IEnumerator LoadAsset(string link, string loadObject)
{
WWW download;
string ErrorMsg=" ";
download = new WWW(link);
yield return download;
if (download.error != null)
{
ErrorMsg=download.error;
}
else
{
ErrorMsg="Downloading ....";
AssetBundle asset = download.assetBundle;
GameObject loadedObject;
loadedObject = Instantiate(asset.Load(loadObject,typeof(GameObject))) as GameObject;
asset.Unload(false);
ErrorMsg="Done";
}
Debug.Log(ErrorMsg);
}
I want to call this method from Main.cs file and return loadedObject in it. Tried to use StartCoroutine
Download download;
download=new Download();
StartCoroutine("download.LoadAsset()");
but without success. Can anybody help me?

Try without the quotes
StartCoroutine( download.LoadAsset() )
You add the quotes when you want to cancel it, but it won't work on a method outside your class.
It would be event better to add a method to your Main.cs that starts the coroutine for you, something like this
public void StartLoadAssetCo()
{
StartCoroutine(LoadAsset());
}
and then just call StartLoadAssetCo from outside the class
download.StartLoadAssetCo();

Related

How to use WriteAllBytes if using UnityWebRequest?

I use UnityWebRequest in getting the file on streamingassets folder because WWW is obsolete, now on FileWriteAllBytes i cant right downloader.bytes because it is return an error to me can someone help me
#if UNITY_ANDROID
// path on streamingasset folder
string path = System.IO.Path.Combine(Application.streamingAssetsPath, "game.dat");
UnityWebRequest downloader = UnityWebRequest.Get(path);
yield return downloader.SendWebRequest();
while (!downloader.isDone)
{
// nothing to be done while downloader gets our db file
}
// then save to application.persistentdatapath
// on this second param i dont know what do right i cant put donwloader.bytes because is obsolete
File.WriteAllBytes(dataFilePath, missing);
#endif
use DownloadHandler
UnityWebRequest downloader = UnityWebRequest.Get(path);
yield return downloader.SendWebRequest();
DownloadHandler handler = downloader.downloadHandler;
File.WriteAllBytes(dataFilePath, handler.data);

Runnable.Run / StartCoroutine calles to Watson services from Unity

In my ExampleStreaming.cs script, once the user utterance is recognized as final, I send it to both the Watson Assistant service and the Tone Analyzer. Because I am keeping the scripts for each service separate as they are, I have to make calls within each script to access the other service. You can see the call I make to the Tone Analyzer below (the .SendToneAnalysis method):
private void OnRecognize(SpeechRecognitionEvent result, Dictionary<string, object> customData)
{
blah blah blah . . .
/// Only send the recognized speech utterance to the
/// Assistant once we know the user has stopped talking.
if (res.final)
{
string _conversationString = alt.transcript;
Runnable.Run( StopRecording(1f) ); // Stop the microphone from listening.
/// Message.
Dictionary<string, object> input = new Dictionary<string, object>
{
["text"] = _conversationString
};
MessageRequest messageRequest = new MessageRequest()
{
Input = input,
Context = _Context
};
_exampleAssistantV1_script.SendMessageAssistant(messageRequest);
_exampleToneAnalyzer.SendToneAnalysis(_conversationString);
. . .
In my ExampleToneAnalyzer.cs script, I make a simple call to the event-handling methods that are meant to contact the service and also handle success & failure:
public void SendToneAnalysis(string conversationString)
{
_service.GetToneAnalyze(OnGetToneAnalyze, OnFail, conversationString);
}
These calls are typically made using StartCoroutines, particularly in the Watson Unity SDK that there is a specialized Runnable.Run which is essentially a helper class for running co-routines without having to inherit from MonoBehavior.
My question is whether my simple method call to the service might be problematic in certain situations or perhaps just wrong or bad programming, or whether it is perfectly OK to go for that method instead of something like the following:
public void SendToneAnalysis(string conversationString)
{
Runnable.Run( SendAssistantToneAnalysis(conversationString) );
}
private IEnumerator SendAssistantToneAnalysis(string conversationString)
{
if ( !_service.GetToneAnalyze(OnGetToneAnalyze, OnFail, conversationString) )
{
Log.Debug("ExampleToneAnalyzer.SendAssistantToneAnalysis()", "Failed to analyze!");
}
while (!_UserUtteranceToneTested)
yield return null;
}
You don't need to make any of the service calls from within a coroutine. Only authentication using iamApikey should be done using a coroutine
IEnumerator TokenExample()
{
// Create IAM token options and supply the apikey. IamUrl is the URL used to get the
// authorization token using the IamApiKey. It defaults to https://iam.bluemix.net/identity/token
TokenOptions iamTokenOptions = new TokenOptions()
{
IamApiKey = "<iam-api-key>",
IamUrl = "<iam-url>"
};
// Create credentials using the IAM token options
_credentials = new Credentials(iamTokenOptions, "<service-url>");
while (!_credentials.HasIamTokenData())
yield return null;
_assistant = new Assistant(_credentials);
_assistant.VersionDate = "2018-02-16";
_assistant.ListWorkspaces(OnListWorkspaces, OnFail);
}
The examples are only meant to show how to invoke the service call. The only reason the code is invoked from a coroutine is so we can wait for the response of one service call before running another service call (i.e. so we don't try to update or delete a workspace before the workspace is created).
It's no problem.
Runnable.Run() eventually calls StartCoroutine() as the follow.
public Routine(IEnumerator a_enumerator)
{
_enumerator = a_enumerator;
Runnable.Instance.StartCoroutine(this);
Stop = false;
ID = Runnable.Instance._nextRoutineId++;
Runnable.Instance._routines[ID] = this;
#if ENABLE_RUNNABLE_DEBUGGING
Log.Debug("Runnable.Routine()", "Coroutine {0} started.", ID );
#endif
}
Please refer to https://github.com/watson-developer-cloud/unity-sdk/blob/master/Scripts/Utilities/Runnable.cs
And the coroutine can be called from any gameobject, if it is active.

create token in unity to send post request to laravel controller

I wanna send a post request from a unity game to a laravel 5.4 controller.. in html form, we use {{csrf_field}} and it handles creating token. but how can I do it in unity?
I came across this thread whilst trying to acheive what it set out to do - and I got it working so I am sharing this:
It is a combination of this tutorial on YouTube: How to Use UnityWebRequest - Replacement for WWW Class - Unity Tutorial and this answer on a similar question: UnityWebRequest POST to PHP not work
The technology I am using:
Laravel Framework 7.15.0 (PHP)
Unity: 2019.3.11f1 (script is C#)
Now I am just sending basic forms not images etc - so I haven't tried anything complex but this sends a get to one URL on Laravel which returns the CSRF token.
This is then added as an additional field to the post request.
I am clicking the 2 buttons pretty quickly - I would suggest (and will implement this myself later) that you don't ask for the token until your ready to submit the form - to avoid it expiring if your form is quite long etc.
The C# Script (Unity)
Both the functions are set as ON Click() on the buttons in a simple UI Canvas in Unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class BasicWebCall : MonoBehaviour
{
public Text messageText;
public InputField scoreToSend;
private string csrf_token;
readonly string getURL = "http://mazegames.test/leaderboard/1";
readonly string postURL = "http://mazegames.test/register/1";
private void Start()
{
messageText.text = "Press buttons to interact with web server";
}
public void OnButtonGetScore()
{
messageText.text = "Getting Token";
StartCoroutine(SimpleGetRequest());
}
IEnumerator SimpleGetRequest()
{
UnityWebRequest www = UnityWebRequest.Get(getURL);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError)
{
Debug.LogError(www.error);
}
else
{
messageText.text = "Token Received: " + www.downloadHandler.text;
csrf_token = www.downloadHandler.text;
}
}
public void OnButtonSendScore()
{
if (scoreToSend.text == string.Empty)
{
messageText.text = "Error: No high score to send.\nEnter a value in the input field.";
}
else
{
messageText.text = "Sending Post Request";
StartCoroutine(SimplePostRequest(scoreToSend.text));
}
}
IEnumerator SimplePostRequest(string curScore)
{
Dictionary<string, string> wwwForm = new Dictionary<string, string>();
wwwForm.Add("_token", csrf_token);
UnityWebRequest www = UnityWebRequest.Post(postURL, wwwForm);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.LogError(www.error);
}
else
{
messageText.text = www.downloadHandler.text;
}
}
}
Laravel routes/web.php
Obviously you need to configure your end points to receive your data, validate and store it if necessary. In this example its just validating the token as part of the post request.
Route::post('register/{game_id}', function($game_id) {
return "Game On!";
});
Route::get('leaderboard/{game_id}', function($game_id) {
return csrf_token();
});
And that is pretty much it - hope this helps someone else.
#EDIT# - Request Token on Submission
To only get the token when your submitting the form, literally all you have to do is put this line:
StartCoroutine(SimpleGetRequest());
above the line:
StartCoroutine(SimplePostRequest(scoreToSend.text));
so that is looks like this:
StartCoroutine(SimpleGetRequest());
StartCoroutine(SimplePostRequest(scoreToSend.text));
Obviously you could then remove the function SimpleGetRequest altogether.
Laravel will generate a token each time a page is generated. The token has a lifetime and after that lifetime it cannot be used anymore (that's the whole point).
You need to get a valid token from Laravel pass it to Unity3D and then when from Unity create a WWWForm and pass it back.
How to do this it depends on the platform that Unity3D is deployed to.
If you are using WebPlayer or WebGL then you can get your hand on the Unity3D objected embedded in the browser and use SendMessage. WebGL link here.
If the game is deployed to another platform it probably makes sense to expose and API on the Laravel side and use that endpoint instead of doing a POST request.
You can use WWWForm to send in POST and call it from a coroutine:
// this will send it at start
// but you can just call SendToController in another function
string laravel_url = "http://somedomain.com/whatever";
IEnumerator Start () {
yield return StartCoroutine(SendToController());
}
IEnumerator SendToController()
{
WWWForm form = new WWWForm();
form.AddField( "csrf_field", "replace this with what you want!!!!" );
WWW download = new WWW( laravel_url, form );
yield return download;
if(!string.IsNullOrEmpty(download.error)) {
print( "Error downloading: " + download.error );
} else {
// if succesful, do what you want
Debug.Log(download.text);
}
}
"Coroutine" is your friend. It will make sending forms a lot easier. You might want to read about it in here:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

How to retrieve Someone's Avatar/Photo with agsXmpp

this is what I have so far:
void xmppConnection_OnReadXml(object sender, string xml)
{
if (xml.Contains(XmlTags.PhotoOpen))
{
int startIndex = xml.IndexOf(XmlTags.PhotoOpen) + XmlTags.PhotoOpen.Length;
int length = xml.IndexOf(XmlTags.PhotoClose) - startIndex;
string photoHash = xml.Substring(startIndex, length);
}
}
I guess I can't undo the hash, but I want to the get a person's avatar/photo. How do I achieve this?
You need to handle the VCard events and responses from XMPP connection:
private void vcardToolStripMenuItem_Click(object sender, EventArgs e)
{
RosterNode node = rosterControl.SelectedItem();
if (node != null)
{
frmVcard f = new frmVcard(node.RosterItem.Jid, XmppCon);
f.Show();
}
}
The above is from the miniclient solution example from the AGSXMPP download. Note, it happens when a user request a VCARD for a user. You can initiate that request whenever you want, however.
private void VcardResult(object sender, IQ iq, object data)
{
if (InvokeRequired)
{
// Windows Forms are not Thread Safe, we need to invoke this :(
// We're not in the UI thread, so we need to call BeginInvoke
BeginInvoke(new IqCB(VcardResult), new object[] { sender, iq, data });
return;
}
if (iq.Type == IqType.result)
{
Vcard vcard = iq.Vcard;
if (vcard!=null)
{
txtFullname.Text = vcard.Fullname;
txtNickname.Text = vcard.Nickname;
txtBirthday.Text = vcard.Birthday.ToString();
txtDescription.Text = vcard.Description;
Photo photo = vcard.Photo;
if (photo != null)
picPhoto.Image = vcard.Photo.Image;
}
}
}
That is what happens when someone requests the VCARD information from XMPP and the IQ type matches the proper data. You can thenpull the photo from vcard.Photo.
You trigger the pull with:
VcardIq viq = new VcardIq(IqType.get, new Jid(jid.Bare));
con.IqGrabber.SendIq(viq, new IqCB(VcardResult), null);
The first line there is the request to the XMPP server, that the VCARD form uses to request user information.
The second line there, sets up another grabber (callback of sorts), that the form uses to wait for the information to arrive, and then parse out the necessary information. IN this case, the grabber is in a new form, so that the main application doesn't have to worry about parsing that information.
You can look at the entire source by extracting the AGSXMPP zip file to your local drive, and looking in the Samples\VS2008\miniclient folder.
You can click link:http://forum.ag-software.de/thread/192-How-to-save-vcard-data

Reading from an assembly with embedded resources

I built an assembly containing one js file.
I marked the file as Embedded Resource and added it into AssemblyInfo file.
I can't refernce the Assembly from a web site. It is in the bin folder but I don't see the reference to it.
It seems like not having at least a class inside the assembly I can't reference it.
I would include the js file into my pages from the assembly.
How should I do this?
Thanks
I do exactly the same thing in one of my projects. I have a central ScriptManager class that actually caches the scripts as it pulls them, but the core of extracting the script file from the embedded resource looks like this:
internal static class ScriptManager
{
private static Dictionary<string, string> m_scriptCache =
new Dictionary<string, string>();
public static string GetScript(string scriptName)
{
return GetScript(scriptName, true);
}
public static string GetScript(string scriptName, bool encloseInCdata)
{
StringBuilder script = new StringBuilder("\r\n");
if (encloseInCdata)
{
script.Append("//<![CDATA[\r\n");
}
if (!m_scriptCache.ContainsKey(scriptName))
{
var asm = Assembly.GetExecutingAssembly();
var stream = asm.GetManifestResourceStream(scriptName);
if (stream == null)
{
var names = asm.GetManifestResourceNames();
// NOTE: you passed in an invalid name.
// Use the above line to determine what tyhe name should be
// most common is not setting the script file to be an embedded resource
if (Debugger.IsAttached) Debugger.Break();
return string.Empty;
}
using (var reader = new StreamReader(stream))
{
var text = reader.ReadToEnd();
m_scriptCache.Add(scriptName, text);
}
}
script.Append(m_scriptCache[scriptName]);
if (encloseInCdata)
{
script.Append("//]]>\r\n");
}
return script.ToString();
}
}
EDIT
To provide more clarity, I've posted my ScriptManager class. To extract a script file, I simply call it like this:
var script = ScriptManager.GetScript("Fully.Qualified.Script.js");
The name you pass in it the full, case-sensitive resource name (the exception handler gets a list of them by calling GetManifestResourceNames()).
This gives you the script as a string - you can then put it out into a file, inject it into the page (which is what I'm doing) or whatever you like.
Assembly myAssembly = // Get your assembly somehow (see below)...
IList<string> resourceNames = myAssembly.GetManifestResourceNames();
This will return a list of all resource names that have been set as 'Embedded Resource'. The name is usually the fully qualified namespace of wherever you put that JS file. So if your project is called My.Project and you store your MyScript.js file inside a folder in your project called Resources, the full name would be My.Project.Resources.MyScript.js
If you then want to use that JS file:
Stream stream = myAssembly.GetManifestResourceStream(myResourceName);
Where myResourceName argument might be "My.Project.Resources.MyScript.js". To get that JS file in that Stream object, you'll need to write it as a file to the hard drive, and serve it from your website as a static file, something like this:
Stream stream = executingAssembly.GetManifestResourceStream(imageResourcePath);
if (stream != null)
{
string directory = Path.GetDirectoryName("C:/WebApps/MyApp/Scripts/");
using (Stream file = File.OpenWrite(directory + "MyScript.js"))
{
CopyStream(stream, file);
}
stream.Dispose();
}
And the code for CopyStream method:
private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
You might want to stick all this code in an Application_Start event in your Global.asax. You don't want it to run for each request
Now getting a reference to your Assembly is a different matter, there are many ways. One way is to include all the above code in your Assembly in question, then make sure you reference that Assembly from your main WebApp project in Visual Studio, then get a reference to the currently executing Assembly like so.
namespace My.Project
{
public class ResourceLoader
{
public static void LoadResources()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
// rest of code from above (snip)
}
}
}
Then call ResourceLoader.LoadResources() from your Application_Start event in your Global.asax.
Hope this helps
Fully working example (I hope):
namespace TestResources.Assembly
{
public class ResourceLoader
{
public static void LoadResources()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream stream = myAssembly
.GetManifestResourceStream("TestResources.Assembly.CheckAnswer.js");
if (stream != null)
{
string directory = Path.GetDirectoryName("C:/WebApps/MyApp/Scripts/");
using (Stream file = File.OpenWrite(directory + "MyScript.js"))
{
CopyStream(stream, file);
}
stream.Dispose();
}
}
private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
}
}
Some caveats:
Change "C:/WebApps/MyApp/" to wherever your web app is located, maybe write some code to work this out dynamically
Make sure the /Scripts folder exists in your webapp root
I think it will overwrite the 'MyScript.js' file if it already exists, but just in case you might want to add some code to check for that file and delete it
Then stick a call to this code in your Global.asax file:
protected void Application_Start()
{
ResourceLoader.LoadResources();
}
Then the path for your web site will be /Scripts/MyScript.js eg:
<head>
<!-- Rest of head (snip) -->
<script type="text/javascript" src="/Scripts/MyScript.js"></script>
</head>